Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return private unique_ptr in public member function

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)?

like image 569
Luigi Pertoldi Avatar asked Mar 11 '17 11:03

Luigi Pertoldi


People also ask

Can you return a unique_ptr from a pointer?

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.

Can a unique_ptr be shared?

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.

Can you pass a unique_ptr by reference in C++?

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.

What are the aliases of unique_ptr in C++?

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 )


1 Answers

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.

like image 198
xtofl Avatar answered Sep 25 '22 05:09

xtofl