std::unique_ptr<T,Deleter>::release

From cppreference.com
< cpp‎ | memory‎ | unique ptr
 
 
Utilities library
General utilities
Date and time
Function objects
Formatting library (C++20)
(C++11)
Relational operators (deprecated in C++20)
Integer comparison functions
(C++20)(C++20)(C++20)   
(C++20)
Swap and type operations
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
Common vocabulary types
(C++11)
(C++17)
(C++17)
(C++17)
(C++11)
(C++17)
(C++23)
Elementary string conversions
(C++17)
(C++17)
 
Dynamic memory management
Smart pointers
(C++11)
(C++11)
(C++11)
(until C++17)
(C++11)
(C++23)
Allocators
Memory resources
Uninitialized storage
Uninitialized memory algorithms
Constrained uninitialized memory algorithms
Garbage collection support
(C++11)(until C++23)
(C++11)(until C++23)
(C++11)(until C++23)
(C++11)(until C++23)
(C++11)(until C++23)
(C++11)(until C++23)
Miscellaneous
(C++20)
(C++11)
(C++11)
 
 
pointer release() noexcept;
(since C++11)
(constexpr since C++23)

Releases the ownership of the managed object, if any.

get() returns nullptr after the call.

The caller is responsible for deleting the object.

Parameters

(none)

Return value

Pointer to the managed object or nullptr if there was no managed object, i.e. the value which would be returned by get() before the call.

Example

#include <memory>
#include <iostream>
#include <cassert>
 
struct Foo {
    Foo() { std::cout << "Foo\n"; }
    ~Foo() { std::cout << "~Foo\n"; }
};
 
int main()
{
    std::cout << "Creating new Foo...\n";
    std::unique_ptr<Foo> up(new Foo());
 
    std::cout << "About to release Foo...\n";
    Foo* fp = up.release();
 
    assert (up.get() == nullptr);
    assert (up == nullptr);
 
    std::cout << "Foo is no longer owned by unique_ptr...\n";
 
    delete fp;
}

Output:

Creating new Foo...
Foo
About to release Foo...
Foo is no longer owned by unique_ptr...
~Foo

See also

returns a pointer to the managed object
(public member function)
replaces the managed object
(public member function)