members of the primary template, unique_ptr<T>
| ||
void reset( pointer ptr = pointer() ); | (1) | |
members of the specialization unique_ptr<T[]>
| ||
void reset( pointer ptr = pointer() ); | (2) | (until C++17) |
(3) | ||
template< class U > void reset( U ) = delete; | (until C++17) | |
template< class U > void reset( U ); | (since C++17) | |
(4) | ||
void reset( std::nullptr_t p ); | (until C++17) | |
void reset( std::nullptr_t p = nullptr ); | (since C++17) |
Replaces the managed object.
current_ptr
, the pointer that was managed by *this
, performs the following actions, in this order: old_ptr = current_ptr
current_ptr = ptr
if(old_ptr != nullptr) get_deleter()(old_ptr)
.
2) Behaves the same as the reset member of the primary template.
3) In the specialization for dynamic arrays, std::unique_ptr<T[]> , this template member is provided to prevent using reset() with a pointer to derived (which would result in undefined behavior with arrays).
4) In the specialization for dynamic arrays,
std::unique_ptr<T[]> , this overload is necessary to allow reset to nullptr (which would otherwise be prohibited by the template overload). Equivalent to reset(pointer()) | (until C++17) |
3) Behaves the same as the reset member of the primary template, except that it will only participate in overload resolution if either
4) Equivalent to
reset(pointer()) | (since C++17) |
ptr | - | pointer to a new object to manage |
(none).
noexcept
specification: noexcept
To replace the managed object while supplying a new deleter as well, move assignment operator may be used.
A test for self-reset, i.e. whether ptr
points to an object already managed by *this
, is not performed, except where provided as a compiler extension or as a debugging assert. Note that code such as p.reset(p.release())
does not involve self-reset, only code like p.reset(p.get())
does.
#include <iostream> #include <memory> struct Foo { Foo() { std::cout << "Foo...\n"; } ~Foo() { std::cout << "~Foo...\n"; } }; struct D { void operator() (Foo* p) { std::cout << "Calling delete for Foo object... \n"; delete p; } }; int main() { std::cout << "Creating new Foo...\n"; std::unique_ptr<Foo, D> up(new Foo(), D()); // up owns the Foo pointer (deleter D) std::cout << "Replace owned Foo with a new Foo...\n"; up.reset(new Foo()); // calls deleter for the old one std::cout << "Release and delete the owned Foo...\n"; up.reset(nullptr); }
Output:
Creating new Foo... Foo... Replace owned Foo with a new Foo... Foo... Calling delete for Foo object... ~Foo... Release and delete the owned Foo... Calling delete for Foo object... ~Foo...
returns a pointer to the managed object and releases the ownership (public member function) |
© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
http://en.cppreference.com/w/cpp/memory/unique_ptr/reset