[英]Does assigning make_unique require std::move() to an empty unique_ptr?
#include <memory>
using namespace std;
int main()
{
unique_ptr<int> a;
// Do something....
// Case 1
a = make_unique<int>(5);
// Case 2
a = std::move(make_unique<int>(5));
return 0;
}
我真正要問的是:
是否需要std :: move將臨時unique_ptr分配給空的unique_ptr? 這兩種情況都可以成功編譯,但我想知道它們之間是否有任何區別。
它不是,因為在這兩種情況下,表達式都可以綁定到右值引用。
在第一個中, std::make_unique
已經返回純rvalue。
在第二個中, std::move
對rvalue引用進行強制轉換,這是多余的。
目標對象是否為空也無關緊要。 僅僅調用賦值的行為並不取決於它所接收的引用是如何綁定的。 結果將是相同的,目標中的先前(可能不存在的)資源將被來自源的“被盜”替換。
你並不需要使用std::move
值分配給一個時std::unique_ptr
通過指針的std :: make_unique 。 這適用於初始化:
std::unique_ptr<int> a = std::make_unique<int>(5);
和任務:
std::unique_ptr<int> a;
a = std::make_unique<int>(5);
該實現已經為您進行了轉發:
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
將
make_unique
指定make_unique
std::move()
是否為空unique_ptr
?
沒有必要是空的,做:
a = make_unique<int>(5);
相當於:
a.reset(make_unique<int>(5));
也就是說,所有的(如果有的話)由對象a
被替換由新創建的一個(被釋放后) make_unique
。
是否需要
std::move
將臨時unique_ptr
分配給空的unique_ptr
?
make_unique
返回的內容:
a = make_unique<int>(5);
已經是右值了。 所以,你不需要使用std::move()
像下面的代碼:
a = std::move(make_unique<int>(5));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.