简体   繁体   中英

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM