(There are three related questions here)
One of the nastiest things I encounter in C++ is accidentally passing/copying an object and then wondering why its state is not what you expect. I recently had a situation where I was passing by pointer, but I was not getting the state I expected and it turned out I had to pass the pointer by reference, which really threw me!
Can I just confirm given this situation:
MyClass x;
AnotherClass y;
y.passMyObjectSomewhere(x);
.
.
.
.
//Later on x is changed and I wish to see this change in y
x.modifyMyObject();
I have the following techniques available to keep the state of x
updated in y
:
MyClass* x = new MyClass();
y.passMyObjectSomewhere(x);
.
.
.
delete x;
or
MyClass x;
y.passMyObjectSomewhere(&x);
or
shared_ptr<MyClass> x(new MyClass());
y.passMyObjectSomewhere(x);
1) and all of the above alternatives will keep x
updated in the y
object, if I make changes to x
outside of y
?
2) Does the above change if x was an object to a vector or another STL collection? Or do the same rules apply?
3) What about a class where a pointer in the constructor is assigned to a data member:
class X{
public:
X(Something* x);
private:
Something* x;
}
X::X(Something* &y){
x = y;
}
Would y
have to be passed in by reference here because otherwise a copy of the pointer would be assigned? I ask this due to another SO question I asked here: