Consider the following class prototype:
class ObjHandler {
std::unique_ptr<Obj> GetPtr() { return obj; }
private:
std::unique_ptr<Obj> obj;
};
This generates a compile-time error saying that the copy constructor of std::unique_ptr
is deleted. Why here move semantics are not applied? Is it related to the fact that GetPtr()
does not own the obj
pointer? How should I implement my code (I need a member function that returns an owning pointer to the stream with the minimum overhead)?
In general, you should not return std::unique_ptr by pointer (ever) or reference (unless you have a specific compelling reason to). If you want the function to take ownership of the contents of the pointer, pass the std::unique_ptr by value.
A unique_ptr does not share its pointer. It cannot be copied to another unique_ptr, passed by value to a function, or used in any C++ Standard Library algorithm that requires copies to be made. A unique_ptr can only be moved.
Although you can pass a std::unique_ptr by reference (which will allow the function to use the object without assuming ownership), you should only do so when the called function might alter or change the object being managed.
The following aliases are member types of unique_ptr. The type of the stored deleter. Exchange content of unique_ptr objects (function template ) Relational operators ==, !=, <, <=, >, >= (function template )
The unique
means actually 'unique ownership'. It makes no sense that you would create a copy of the ownership, since then it would not be unique anymore.
What you probably want is returning a reference to the contained object, or a non owning pointer:
class ObjHandler {
Object &get(){ return *obj; }
Object *GetPtr() { return obj.get(); }
private:
unique_ptr<Object> obj;
};
This post is a very good talk on the what/where/why of using smart pointers.
And the CppCoreGuidelines have a hint on this, too: a raw pointer is by definition indication of the fact that the object is not owned.
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