名稱空間
變體
操作

std::unique_ptr<T,Deleter>::operator=

來自 cppreference.com
< cpp‎ | memory‎ | unique ptr
 
 
記憶體管理庫
(僅作說明*)
未初始化記憶體演算法
(C++17)
(C++17)
(C++17)
受約束的未初始化
記憶體演算法
C 庫

分配器
記憶體資源
垃圾回收支援
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
未初始化儲存
(直到 C++20*)
(直到 C++20*)
顯式生命週期管理
 
 
unique_ptr& operator=( unique_ptr&& r ) noexcept;
(1) (自 C++23 起為 constexpr)
template< class U, class E >
unique_ptr& operator=( unique_ptr<U, E>&& r ) noexcept;
(2) (自 C++23 起為 constexpr)
unique_ptr& operator=( std::nullptr_t ) noexcept;
(3) (自 C++23 起為 constexpr)
unique_ptr& operator=( const unique_ptr& ) = delete;
(4)
1) 移動賦值運算子。將所有權從 r 轉移到 *this,如同透過呼叫 reset(r.release()),然後賦值 get_deleter()std::forward<Deleter>(r.get_deleter())
此過載僅當 std::is_move_assignable<Deleter>::valuetrue 時才參與過載決議。
Deleter 不是引用型別,則若以下條件之一為真,行為未定義:
否則(Deleter 是引用型別),若以下條件之一為真,行為未定義:
2) 轉換賦值運算子。將所有權從 r 轉移到 *this,如同透過呼叫 reset(r.release()),然後賦值 get_deleter()std::forward<E>(r.get_deleter())
僅當滿足以下所有條件時,此過載才參與過載決議
  • std::is_assignable<Deleter&, E&&>::valuetrue
  • 對於主模板,所有以下條件都得到滿足:
    • U 不是陣列型別。
    • unique_ptr<U, E>::pointer 可隱式轉換為 pointer
  • 對於陣列特化(unique_ptr<T[]>),所有以下條件都得到滿足:
    • U 是陣列型別。
    • pointerelement_type* 型別相同。
    • unique_ptr<U, E>::pointerunique_ptr<U, E>::element_type* 型別相同。
    • unique_ptr<U, E>::element_type(*)[] 可轉換為 element_type(*)[]
E 不是引用型別,則若從 E 型別的右值賦值 get_deleter() 非良構或會丟擲異常,行為未定義。
否則(E 是引用型別),則若從 E 型別的左值賦值 get_deleter() 非良構或會丟擲異常,行為未定義。
3) 效果上等同於呼叫 reset()
4) 複製賦值運算子被顯式刪除。

目錄

[編輯] 引數

r - 將從中轉移所有權的智慧指標

[編輯] 返回值

*this

[編輯] 注意

作為僅移動型別,unique_ptr 的賦值運算子只接受右值引數(例如 std::make_unique 的結果或經過 std::moveunique_ptr 變數)。

[編輯] 示例

#include <iostream>
#include <memory>
 
struct Foo
{
    int id;
    Foo(int id) : id(id) { std::cout << "Foo " << id << '\n'; }
    ~Foo() { std::cout << "~Foo " << id << '\n'; }
};
 
int main() 
{
    std::unique_ptr<Foo> p1(std::make_unique<Foo>(1));
 
    {
        std::cout << "Creating new Foo...\n";
        std::unique_ptr<Foo> p2(std::make_unique<Foo>(2));
        // p1 = p2; // Error ! can't copy unique_ptr
        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";
}

輸出

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

[編輯] 缺陷報告

下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。

缺陷報告 應用於 釋出時的行為 正確的行為
LWG 2047 C++11 對於過載 (2)get_deleter() 從以下內容賦值:
std::forward<Deleter>(r.get_deleter())
更正為
std::forward<E>(r.get_deleter())
LWG 2118 C++11 unique_ptr<T[]>::operator=
拒絕限定轉換
接受
LWG 2228
(N4366)
C++11 轉換賦值運算子
缺少可賦值性約束
添加了約束
LWG 2246 C++11 轉換後的賦值目標
r 的刪除器未指定
指定為 get_deleter()
LWG 2899 C++11 移動賦值運算子未受約束 已受約束