std::unique_ptr<T,Deleter>::release
來自 cppreference.com
< cpp | memory | unique ptr
pointer release() noexcept; |
(C++11 起) (C++23 起為 constexpr) |
|
釋放所管理物件的所有權(如果有)。
呼叫後,get() 返回 nullptr。
呼叫者負責清理物件(例如,透過使用 get_deleter())。
目錄 |
[編輯] 引數
(無)
[編輯] 返回值
指向被管理物件的指標,如果沒有被管理物件則為 nullptr,即呼叫前 get() 將返回的值。
[編輯] 示例
執行此程式碼
#include <cassert> #include <iostream> #include <memory> struct Foo { Foo() { std::cout << "Foo\n"; } ~Foo() { std::cout << "~Foo\n"; } }; // Ownership of the Foo resource is transferred when calling this function void legacy_api(Foo* owning_foo) { std::cout << __func__ << '\n'; // [legacy code that no one understands or dares touch anymore] // [...] delete owning_foo; } int main() { std::unique_ptr<Foo> managed_foo(new Foo); // [code that might return or throw or some such] // [...] legacy_api(managed_foo.release()); assert(managed_foo == nullptr); }
輸出
Foo legacy_api ~Foo
[編輯] 參閱
返回指向託管物件的指標 (public member function) | |
返回用於銷燬託管物件的刪除器 (public member function) | |
替換託管物件 (public member function) |