std::unique_ptr::operator=

来自cppreference.com
< cpp‎ | memory‎ | unique ptr

 
 
 
 
 
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 起)
1)
所有权转让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()).
文本通过谷歌翻译机器翻译。
你可以帮忙校正和验证翻译。点击此处查看指示。
2)
实际上是相同的调用reset().
原文:
Effectively the same as calling reset().
文本通过谷歌翻译机器翻译。
你可以帮忙校正和验证翻译。点击此处查看指示。
需要注意的是unique_ptr的赋值操作符只接受xvalues​​,这是通常由std::move。 (unique_ptr类显式删除其左值拷贝构造函数和左值赋值运算符)
原文:
Note that unique_ptr's assignment operator only accepts xvalues​​, which are typically generated by std::move. (The unique_ptr class explicitly deletes its 左值 copy constructor and 左值 assignment operator.)
文本通过谷歌翻译机器翻译。
你可以帮忙校正和验证翻译。点击此处查看指示。

目录

[编辑] 参数

r -
智能指针的所有权将被转移
原文:
smart pointer from which ownership will be transfered
文本通过谷歌翻译机器翻译。
你可以帮忙校正和验证翻译。点击此处查看指示。

[编辑] 返回值

*this

[编辑] 异常

noexcept 规定:  
noexcept
  

[编辑] 示例

#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