The unique_ptr shall not be empty (i.e., its stored pointer shall not be a null pointer) in order to be dereferenciable. This can easily be checked by casting the unique_ptr object to bool (see unique_ptr::operator bool). It is equivalent to: *get().
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.
unique_ptr. An unique_ptr has exclusive ownership of the object it points to and will destroy the object when the pointer goes out of scope.
You need to move the unique_ptr
:
vec.push_back(std::move(ptr2x));
unique_ptr
guarantees that a single unique_ptr
container has ownership of the held pointer. This means that you can't make copies of a unique_ptr
(because then two unique_ptr
s would have ownership), so you can only move it.
Note, however, that your current use of unique_ptr
is incorrect. You cannot use it to manage a pointer to a local variable. The lifetime of a local variable is managed automatically: local variables are destroyed when the block ends (e.g., when the function returns, in this case). You need to dynamically allocate the object:
std::unique_ptr<int> ptr(new int(1));
In C++14 we have an even better way to do so:
make_unique<int>(5);
std::unique_ptr has no copy constructor. You create an instance and then ask the std::vector to copy that instance during initialisation.
error: deleted function 'std::unique_ptr<_Tp, _Tp_Deleter>::uniqu
e_ptr(const std::unique_ptr<_Tp, _Tp_Deleter>&) [with _Tp = int, _Tp_D
eleter = std::default_delete<int>, std::unique_ptr<_Tp, _Tp_Deleter> =
std::unique_ptr<int>]'
The class satisfies the requirements of MoveConstructible and MoveAssignable, but not the requirements of either CopyConstructible or CopyAssignable.
The following works with the new emplace calls.
std::vector< std::unique_ptr< int > > vec;
vec.emplace_back( new int( 1984 ) );
See using unique_ptr with standard library containers for further reading.
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