I have a question:
class B : public class A {
public:
vector<int*> vec;
};
class A {
};
vector<A*> vec_a;
vector<B*> vec_b;
if I push back an object of class B into both vectors.
B* b = new B;
vec_a.push_back(b);
vec_b.push_back(b);
then after that, I change something inside the object of class B,
such as:
int* i = ....
vec_b[0].push_back(i);
Does the vec_a change?
I am confused with that since I have checked that when vector push_back, it will only create a copy. But when I checked with the above codes, it changes. Are the two vectors hold a shared memory of object b?
Thanks
Your vectors contain pointers to a common object. Therefore anything you change inside that object via a derefence of one of those pointers is reflected in the object that they are pointing to. Adding the pointers to the vectors creates a copy of the pointers themselves, not the object they point to. Had you added a common instance of class
Bto both vectors, each vector would contain a separate copy of that object. Adding pointers results copies of your original pointer being added to each vector – but both copies will have the same value and that is the memory address of the object they point to.