std::unique_ptr::release

std::unique_ptr::release

pointer release();
(since C++11)

Releases the ownership of the managed object if any. get() returns nullptr after the call.

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.

Exceptions

noexcept specification:
noexcept

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);
    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)

© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
http://en.cppreference.com/w/cpp/memory/unique_ptr/release

在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号

意见反馈
返回顶部