Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will the original object get deleted if I return a unique_ptr?

Tags:

c++

unique-ptr

I want to do something like this:

unique_ptr<MyObj> MyFunc() {
  MyObj* ptr = new MyObj();
  ...
  return unique_ptr<MyObj>(ptr);
}

unique_ptr<MyObj> value = MyFunc();

But I'm unsure if the object will be deleted when the temporary value was destructed after the function returns. If so, how should I implement correctly a function that returns a unique_ptr?

like image 548
OneZero Avatar asked Jan 04 '16 18:01

OneZero


1 Answers

No, the object will not be deleted when function scope ends. This is because move constructor of unique_ptr will 'move' the ownership semantics to the new unique_ptr object, and destruction of the old unique_ptr will not cause deletion of the allocated object.

Note: This is not the right way of doing this. If there is an exception thrown between the point of memory allocation and unique_ptr<> creation you will have a memory leak.

like image 176
SergeyA Avatar answered Nov 03 '22 00:11

SergeyA