std::unique_ptr::operator=

初等模板 unique_ptr<T> 的成员
unique_ptr& operator=( unique_ptr&& r ) noexcept;
(1)
template< class U, class E >
unique_ptr& operator=( unique_ptr<U,E>&& r ) noexcept;
(1)
unique_ptr& operator=( nullptr_t ) noexcept;
(2)
数组特化 unique_ptr<T[]> 的成员
unique_ptr& operator=( unique_ptr&& r ) noexcept;
(1)
template< class U, class E >
unique_ptr& operator=( unique_ptr<U,E>&& r ) noexcept;
(1) (C++17 起)
unique_ptr& operator=( nullptr_t ) noexcept;
(2)
1)r 转移所有权到 *this ,如同以调用 reset(r.release()) 后随从 get_deleter()std::forward<E>(r.get_deleter()) 的赋值。
Deleter 不是引用类型,则要求它为不抛出可移动赋值 (MoveAssignable) 。
Deleter 是引用类型,则要求 std::remove_reference<Deleter>::type 为不抛出可复制赋值 (CopyAssignable) 。
此赋值运算符的模板版本仅若 U 非数组类型且 unique_ptr<U,E>::pointer 可隐式转换为 pointer std::is_assignable<Deleter&, E&&>::valuetrue (C++17 起)才参与重载决议。
数组的特化 std::unique_ptr<T[]> 中,此赋值运算符的模板版本表现与初等模板中相同,除了仅若下列皆为真才参与重载决议:
* U 是数组类型
* pointerelement_type* 是同一类型
* unique_ptr<U,E>::pointerunique_ptr<U,E>::element_type* 是同一类型
* unique_ptr<U,E>::element_type(*)[] 可转换为 element_type(*)[]
* std::is_assignable<Deleter&, E&&>::valuetrue
(C++17 起)
2) 与调用 reset() 等效。

注意 unique_ptr 的赋值运算符只接受典型地由 std::move 生成的右值。( unique_ptr 类显式删除其左值复制构造函数和左值赋值运算符。)

参数

r - 所有权将被转移的智能指针

返回值

*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( std::make_unique<Foo>() );
        // p1 = p2; // 错误!不能复制 unique_ptr
        p1 = std::move(p2);
        std::cout << "About to leave inner block...\n";
 
        // Foo 实例将继续生存,尽管 p2 离开作用域
    }
 
    std::cout << "About to leave program...\n";
}

输出:

Creating new Foo...
Foo
About to leave inner block...
About to leave program...
~Foo

版本历史

  • (当前 | 先前 2017年9月11日 (一) 08:34Fruderica讨论 | 贡献. . (3,359字节) (+505). . (撤销)
  • 当前 | 先前 2015年7月21日 (二) 04:24180.212.102.62讨论. . (2,854字节) (0). . (fix translation) (撤销)
  • 当前 | 先前 2014年10月26日 (日) 17:58P12bot讨论 | 贡献 . . (2,854字节) (0). . (Fix some translations) (撤销)
  • 当前 | 先前 2013年7月2日 (二) 09:08P12bot讨论 | 贡献 . . (2,854字节) (-114). . (Use {{lc}}. Update links. Various fixes.) (撤销)
  • 当前 | 先前 2012年11月2日 (五) 14:15P12bot讨论 | 贡献 . . (2,968字节) (+313). . (r2.7.3) (机器人添加:de, en, es, fr, it, ja, pt, ru) (撤销)
  • 当前 | 先前 2012年10月27日 (六) 03:41P12讨论 | 贡献 . . (2,655字节) (0). . (1个修订: Translate from the English version) (撤销)
  • 当前 | 先前 2012年10月26日 (五) 06:00TranslationBot讨论 | 贡献. . (2,655字节) (-84). . (Translated from the English version using Google Translate) (撤销)
  • 当前 | 先前 2012年10月25日 (四) 14:56P12讨论 | 贡献 . . (2,739字节) (0). . (1个修订: Translate from the English version) (撤销)
  • 当前 | 先前) 2012年10月25日 (四) 12:00TranslationBot讨论 | 贡献. . (2,739字节) (+2,739). . (Translated from the English version using Google Translate)