c++ how to convert already created object to unique_ptr

MyClass myObject = something.get(id);

Implies either copy or move construction.

If your copy constructor is defined and declared public try the following

std::unique_ptr<MyClass> my_p_obj( new MyClass(myObject) );

Where you create a new object and initialize it by copying.

Otherwise the object in your example is initialized through move construction

std::unique_ptr<MyClass> my_p_obj( new MyClass( std::move(myObject) ) );

what's wrong with std::unique_ptr(&myObject);

myObject is an object in the local scope which will be destroyed when the function it lies in reaches the end (}). If you call the destructor twice (one from the compiler, the second from unique_ptr) you get undefined behaviour

Edit : As cleared up in the comments, you could make use of auto my_p_obj = std::make_unique<MyClass>(myObject) which does the same thing. – Thanks, Andreas H.

Tags:

C++

Unique Ptr