std::unique_ptr::reset
来自cppreference.com
< cpp | memory | unique ptr
该页由英文版wiki使用Google Translate机器翻译而来。
该翻译可能存在错误或用词不当。鼠标停留在文本上可以看到原版本。你可以帮助我们修正错误或改进翻译。参见说明请点击这里. |
void reset( pointer ptr = pointer() ); |
(C++11 起) | |
Replaces the managed object.
Given current_ptr
, the pointer that was managed by *this
, performs the following actions, in this order:
- Saves a copy of the current pointer old_ptr = current_ptr
- Overwrites the current pointer with the argument current_ptr = ptr
- If the old pointer was non-empty, deletes the previously managed object if(old_ptr != nullptr) get_deleter()(old_ptr).
目录 |
[编辑] 参数
ptr | - | pointer to a new object to manage |
[编辑] 返回值
(无)
[编辑] 注释
To replace the managed object while supplying a new deleter as well, move assignment operator may be used.
A test for self-reset, i.e. whether ptr
points to an object already managed by *this
, is not performed, except where provided as a compiler extension or as a debugging assert. Note that code such as p.reset(p.release()) does not involve self-reset, only code like p.reset(p.get()) does.
[编辑] 示例
#include <iostream> #include <memory> struct Foo { Foo() { std::cout << "Foo...\n"; } ~Foo() { std::cout << "~Foo...\n"; } }; struct D { void operator() (Foo* p) { std::cout << "Calling delete for Foo object... \n"; delete p; } }; int main() { std::cout << "Creating new Foo...\n"; std::unique_ptr<Foo, D> up(new Foo(), D()); // up owns the Foo pointer (deleter D) std::cout << "Replace owned Foo with a new Foo...\n"; up.reset(new Foo()); // calls deleter for the old one std::cout << "Release and delete the owned Foo...\n"; up.reset(nullptr); }
输出:
Creating new Foo... Foo... Replace owned Foo with a new Foo... Foo... Calling delete for Foo object... ~Foo... Release and delete the owned Foo... Calling delete for Foo object... ~Foo...
[编辑] 另请参阅
返回一个指针,指向被管理对象,并释放所有权 原文: returns a pointer to the managed object and releases the ownership (公共成员函数) |