Little Endian
Little Endian

Reputation: 830

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?

Upvotes: 3

Views: 108

Answers (2)

juanchopanza
juanchopanza

Reputation: 227418

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";

Upvotes: 2

Elazar
Elazar

Reputation: 21615

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.

Upvotes: 2

Related Questions