std::unique_ptr::operator=
来自cppreference.com
< cpp | memory | unique ptr
该页由英文版wiki使用Google Translate机器翻译而来。
该翻译可能存在错误或用词不当。鼠标停留在文本上可以看到原版本。你可以帮助我们修正错误或改进翻译。参见说明请点击这里. |
unique_ptr& operator=( unique_ptr&& r ); |
(1) | (C++11 起) |
template< class U, class E > unique_ptr& operator=( unique_ptr<U,E>&& r ); |
(1) | (C++11 起) |
unique_ptr& operator=( nullptr_t ); |
(2) | (C++11 起) |
所有权转让
2) r
到*this所指向的对象因为如果调用reset(r.release())std::forward<E>(r.get_deleter())的分配。 原文:
Transfers ownership of the object pointed to by
r
to *this as if by calling reset(r.release()) followed by an assignment from std::forward<E>(r.get_deleter()). 实际上是相同的调用reset().
原文:
Effectively the same as calling reset().
需要注意的是
unique_ptr
的赋值操作符只接受xvalues,这是通常由std::move。 (unique_ptr
类显式删除其左值拷贝构造函数和左值赋值运算符)目录 |
[编辑] 参数
r | - | 智能指针的所有权将被转移
原文: smart pointer from which ownership will be transfered |
[编辑] 返回值
*this
[编辑] 例外
[编辑] 示例
#include <iostream> #include <memory> struct Foo { Foo() { std::cout << "Foo\n"; } ~Foo() { std::cout << "~Foo\n"; } }; int main() { std::unique_ptr<Foo> p1; { std::cout << "Creating new Foo...\n"; std::unique_ptr<Foo> p2(new Foo); p1 = std::move(p2); std::cout << "About to leave inner block...\n"; // Foo instance will continue to live, // despite p2 going out of scope } std::cout << "About to leave program...\n"; }
输出:
Creating new Foo... Foo About to leave inner block... About to leave program... ~Foo