Convert object to std :: unique_ptr

I have a simple question that I can not find the answer to:

In C ++, how to convert a regular object

int i; 

in a std::unique_ptr ?

 std::unique_ptr<int> iptr = &i; //invalid std::unique_ptr<int> iptr = static_cast<std::unique_ptr<int>>(&i); //invalid 

Thanks.

+6
source share
4 answers

Not. This object cannot be deleted with delete , which unique_ptr will do. You need

 auto iptr = make_unique<int>(); 

Here we define make_unique as a utility function identical to make_shared, which was supposed to be standard, but unfortunately was missed. Here's a summary:

 template<typename T, typename... Args> std::unique_ptr<T> make_unique(Args&&... args) { return std::unique_ptr<T>(new T(std::forward<Args>(args)...)); } 
+11
source

Not. i not dynamically allocated, so it does not need to be deleted. If you close the smart pointer around your address, at some point it will do delete &i and give you undefined behavior. You should only wrap something that you have new ed in a smart pointer, for example:

 std::unique_ptr<int> ptr(new int(5)); 

The whole point of a smart pointer is that it controls the lifetime of a dynamically allocated object for you. i has an automatic storage duration, so it will be destroyed at the end of its area. You do not need anything to help you with this.

+4
source

I believe this will work:

 int i; auto deleter = [](int *ptr){}; std::unique_ptr<int, decltype(deleter)> iptr(&i, deleter); 

You must provide a custom divector that does nothing. The default deliter cannot delete an automatic variable not allocated by new . (However, this defeats the purpose of using a smart pointer, but shows that this is possible).

+1
source

When unique_ptr is destroyed, what will happen? Or else, when a variable goes out of scope? It makes no sense.

0
source

All Articles