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
?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With