Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ how to convert already created object to unique_ptr

Tags:

c++

unique-ptr

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?
like image 730
user3828398 Avatar asked May 12 '16 08:05

user3828398


People also ask

Can you convert shared_ptr to unique_ptr?

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 .

How do you create a unique PTR from an object?

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.

Can a unique_ptr be copied?

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.

How do I transfer ownership of unique PTRS?

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.


1 Answers

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.

like image 101
george_ptr Avatar answered Oct 10 '22 21:10

george_ptr