Namespaces
Variants

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

From cppreference.net
Memory management library
( exposition only* )
Allocators
Uninitialized memory algorithms
Constrained uninitialized memory algorithms
Memory resources
Uninitialized storage (until C++20)
( until C++20* )
( until C++20* )
( until C++20* )

Garbage collector support (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)
(C++11) (until C++23)
pointer release ( ) noexcept ;
(C++11以降)
(constexpr C++23以降)

管理されているオブジェクトの所有権がある場合、それを解放します。

get() 呼び出し後に nullptr を返します。

呼び出し側はオブジェクトのクリーンアップ責任を負います(例: get_deleter() の使用による)。

目次

パラメータ

(なし)

戻り値

管理対象オブジェクトへのポインタ、または管理対象オブジェクトが存在しない場合(つまり、呼び出し前に get() によって返される値)は nullptr です。

#include <cassert>
#include <iostream>
#include <memory>
struct Foo
{
    Foo() { std::cout << "Foo\n"; }
    ~Foo() { std::cout << "~Foo\n"; }
};
// Fooリソースの所有権はこの関数呼び出し時に移譲される
void legacy_api(Foo* owning_foo)
{
    std::cout << __func__ << '\n';
    // [誰も理解せず、触れることを恐れるレガシーコード]
    // [...]
    delete owning_foo;
}
int main()
{
    std::unique_ptr<Foo> managed_foo(new Foo);
    // [returnしたり例外を投げたりする可能性のあるコード]
    // [...]
    legacy_api(managed_foo.release());
    assert(managed_foo == nullptr);
}

出力:

Foo
legacy_api
~Foo

関連項目

管理対象オブジェクトへのポインタを返す
(public member function)
管理対象オブジェクトの破棄に使用されるデリーターを返す
(public member function)
管理対象オブジェクトを置き換える
(public member function)