0

(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:

Pointer to pointer assignment isnt working

Community
  • 1
  • 1
user997112
  • 29,025
  • 43
  • 182
  • 361

1 Answers1

1

1) Yes, they should if you store a pointer to your x. But be careful in your 2 first examples, y seems to be able to outlive x. The pointer in ywon't know that the object pointed will be deleted and this will certainly cause a crash:

MyClass* x = new MyClass();
y.passMyObjectSomewhere(x);
.
// update x
y.doesSomeActionOnX(); // no crash
delete x;
y.doesSomeActionOnX(); // crash

The std::shared_ptr is a better option as it does handle ownership sharing. BTW you can do:

auto x = std::make_shared<MyClass>();

2) Same rules everywhere.

3) Your reference is totally useless here.

X::X(Something* y)
{ 
  this.y = y;
}
Johan
  • 3,728
  • 16
  • 25
  • Regarding #3 did I mis-read something in the SO question I asked a few weeks ago (linked in my question here) then? – user997112 Nov 16 '13 at 18:33
  • Your other question was the other way around you wanted to modify the pointer given as parameter. – Johan Nov 16 '13 at 19:40