[英]Understanding std::move and unique_ptr
我是c ++ 11的新手,並試圖了解std::move
和unique_ptr
含義,並編寫了以下代碼,我以兩種不同的方式在unique_ptr
上使用std::move
:
void unique_ptr_plain_move() {
unique_ptr<int> intptr(new int(10));
unique_ptr<int> intptr2;
printf("*intptr = %d\n", *intptr);
intptr2 = std::move(intptr);
printf("*intptr2 = %d\n", *intptr2);
// as expected, crash here as we have already moved intptr's ownership.
printf("*intptr = %d\n", *intptr);
}
/////////////////////////////////////////////
void function_call_move(unique_ptr<int>&& intptr) {
printf("[func] *intptr = %d\n", *intptr);
}
void unique_ptr_function_call_move() {
unique_ptr<int> intptr(new int(10));
printf("*intptr = %d\n", *intptr);
function_call_move(std::move(intptr));
// this does not crash, intptr still has the ownership of its pointed instance ....
printf("*intptr = %d\n", *intptr);
}
在unique_ptr_plain_move()
, intptr2
在std::move
之后獲得intptr
的所有權,因此我們不能再使用intptr
。 但是,在unique_ptr_function_call_move()
,在函數調用中使用std::move
時, intptr
仍然擁有其指向實例的所有權。 我知道將std::move(unique_ptr)
傳遞給函數時到底發生了什么嗎? 謝謝。
這里的關鍵概念是std::move
本身不會做任何移動。 您可以將其視為將對象標記為可以移動的對象。
function_call_move
的簽名為
void function_call_move( unique_ptr<int>&& ptr );
這意味着它只能接收可以從中移動的對象(正式稱為rvalues)並將其綁定到引用。 將右值與右值引用關聯的行為也不會使原始對象的狀態無效。
因此,除非function_call_move
實際上將ptr
移到其中的另一個std::unique_ptr
,否則您對function_call_move(std::move(intptr));
調用會被調用function_call_move(std::move(intptr));
不會使intptr
無效,並且您的用法將完全正確。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.