Nikolai’s answer is absolutely right. Like ereOn.
You also need to consider the difference between passing by value and passing by reference.
If SomeFunc was declared as:
void SomeFunc(Sample& x)
or even better
void SomeFunc(const Sample& x)
you would not have a problem with a dangling pointer.
As you defined SomeFunc , the Sample object is passed by value, which means that the temporary copy is intended to be used within the scope of SomeFunc . Then, when SomeFunc returns a temporary object, it goes out of scope, and its destructor is called, which removes the integer pointed to by ptr .
If you pass a reference to the Sample object, then when SomeFunc called SomeFunc copies will not be created, and therefore, no destructor will be called when SomeFunc .
Seb rose
source share