Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Trouble accessing an object from a vector

I'm new to C++, so this is probably an easy question. I have a vector of vectors declared in the class Predictor:

class Predictor{
    std::vector<std::vector<BitCounter>> data;
public:
    Predictor();
    void addBit(int x);
};

BitCounter is declared as:

class BitCounter {
    short int count0 = 0;
    short int count1 = 0;
public:
    BitCounter();
    short int getCount0();
    short int getCount1();
    void addBit(int x);
};

In Predictor::addBit, I have the lines:

BitCounter bit_counter = data[i][j];
printf("%p %p\n", &bit_counter, &data[i][j]);

This gives me two distinct addresses, where I was expecting to get identical addresses. What boneheaded error am I making?

like image 394
Little Endian Avatar asked Dec 29 '25 09:12

Little Endian


2 Answers

This makes a BitCounter copy:

BitCounter bit_counter = data[i][j];

Here, bit_counter is a copy of whatever is in data[i][j], and therefore has a different address.

If you want to reference the element in your nested vector, you can use a reference instead:

const BitCounter& bit_counter = data[i][j];

Here, bit_counter is an alias for whatever is in data[i][j] and therefore the address-of operator will yield the same address for both:

const BitCounter& bit_counter = data[i][j];
std::cout << &bit_counter << "\n";
std::cout << &data[i][j] << "\n";
like image 185
juanchopanza Avatar answered Dec 30 '25 22:12

juanchopanza


These are two distinct objects. &bit_counter is the address of the local variable, where &data[i][j] is the address of the object inside Vector.

BitCounter bit_counter = data[i][j]; means "construct a new BitCounter object using the value of data[i][j]". The main difference between this and new BitCounter(data[i][j]) (which is somewhat more similar to things happen in Java/C#) is that in our case the lifetime of the object is limited by the scope of the variable - namely, the current block.

So, if you want to get similar (but not identical) behavior to Java, you should use a pointer type, which makes the printf statement obvoius:

BitCounter* bit_counter = &data[i][j];
printf("%p %p\n", bit_counter, &data[i][j]);

you can use references, as suggested here:

const BitCounter& bit_counter = data[i][j];
printf("%p %p\n", &bit_counter, &data[i][j]);

but note that a reference cannot be changed, unlike the case with references in Java/C#, so an assignment to bit_counter (if it was not constant) will change the referenced object itself.

like image 22
Elazar Avatar answered Dec 30 '25 22:12

Elazar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!