Reputation: 565
I have a get
function which returns an object of type MyClass
called myObject
:
MyClass myObject = something.get(id);
I want to convert myObject
to unique_ptr
, how to do it?
std::unique_ptr<MyClass>(&myObject); // Is this correct?
Upvotes: 18
Views: 32040
Reputation: 629
If you would initialize it with the reference, it would give problems when you get out of scope. One possibility:
// Example program
#include <iostream>
#include <string>
#include <memory>
struct MyClass
{
};
int main()
{
MyClass myObject;
std::unique_ptr<MyClass>( new MyClass(myObject) );
}
Upvotes: 0
Reputation: 598
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.
Upvotes: 20