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?
In short, you can easily and efficiently convert a std::unique_ptr to std::shared_ptr but you cannot convert std::shared_ptr to std::unique_ptr .
auto ptr = make_unique<int>(); // Create a new unique_ptr object. auto ptr = make_unique<int>(); The dynamically allocated object is destroyed when the created unique pointer object is destroyed.
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.
In C++11 we can transfer the ownership of an object to another unique_ptr using std::move() . After the ownership transfer, the smart pointer that ceded the ownership becomes null and get() returns nullptr.
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.
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