跳到主要内容

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

自 C++11 起
pointer release() noexcept; 
自 C++23 起
constexpr pointer release() noexcept;

释放所管理对象的拥有权(如果存在)。

调用后 get() 返回 nullptr

调用者负责删除该对象。

参数

(无)

返回值

指向所管理对象的指针,或者在没有管理对象的情况下返回 nullptr,即调用前 get() 将返回的值。

示例

#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;
}

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

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

自 C++11 起
pointer release() noexcept; 
自 C++23 起
constexpr pointer release() noexcept;

释放所管理对象的拥有权(如果存在)。

调用后 get() 返回 nullptr

调用者负责删除该对象。

参数

(无)

返回值

指向所管理对象的指针,或者在没有管理对象的情况下返回 nullptr,即调用前 get() 将返回的值。

示例

#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;
}

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