Reputation: 2046
Does it ever make sense to create a std::unique_ptr
using new
? In the snippet below as I suspected the SimpleClass
object being managed by the std::unique_ptr
won't be destroyed unless I delete the std::unique_ptr
myself. I couldn't think of a situation where this is useful so I was wondering if there are situations where this is actually used.
std::unique_ptr<vector_test::SimpleClass>* ptr_to_unique_ptr = new std::unique_ptr<vector_test::SimpleClass>();
ptr_to_unique_ptr->reset(new vector_test::SimpleClass(555));
delete ptr_to_unique_ptr;
Upvotes: 4
Views: 1755
Reputation: 27796
Does it ever make sense to create a std::unique_ptr using new?
I can't think of. There are situations where you want to prevent an object managed through a unique_ptr
from deletion, when the scope that contains the unique_ptr
ends. There are several ways to do this, without having to new
the unique_ptr
itself.
Some examples:
Move the object to another unique_ptr
in a different scope.
std::unique_ptr<int> p1;
{
std::unique_ptr<int> p2 = std::make_unique<int>( 42 );
p1 = std::move( p2 );
// Destructor of p2 won't delete object, because ownership was transferred.
}
// Scope of p2 has ended, but object is still managed by p1.
std::cout << *p1;
Return an object managed through a unique_ptr
from a function.
std::unique_ptr<int> MyFun() {
std::unique_ptr<int> p = std::make_unique<int>( 42 );
return p; // No explicit move required, because of RVO
}
Release ownership and get the raw pointer back.
std::unique_ptr<int> p = std::make_unique<int>( 42 );
some_C_API_that_takes_ownership( p.release() );
// Destructor of p won't delete object, because ownership was given up.
Upvotes: 1
Reputation: 1
Does it ever make sense to create a
std::unique_ptr
usingnew
?
Most probably not.
There's no concise reason why you would/should fall back to manual memory management while already using the standard dynamic memory allocation techniques.
I couldn't think of a situation where this is useful so I was wondering if there are situations where this is actually used.
I can't timagine either about such situation.
Upvotes: 2
Reputation: 238461
There is rarely a use for dynamically allocating a singular pointer. Closest real word use case is a singly linked list, where we dynamically allocate a class instance that contains a pointer, and some data associated with the node. Although, need to implement a linked list is rare because it is rarely the optimal choice of data structure, and because the standard library already provides decent designs of linked list.
Note that if we were to dynamically allocate a (smart) pointer, there is no good reason to not use a smart pointer to manage that allocation.
Upvotes: 1