我是c ++ 11的新手并尝试理解std::move
和unique_ptr
的含义,并编写了以下代码,我在std::move
上使用unique_ptr
以两种不同的方式:
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
在intptr
之后获得std::move
的所有权,因此我们无法再使用intptr
。但是,在unique_ptr_function_call_move()
中,在函数调用中使用std::move
时,intptr
仍然拥有其指向实例的所有权。当我们将std::move(unique_ptr)
传递给函数时,我能知道到底发生了什么吗?谢谢。
答案 0 :(得分:4)
这里的关键概念是std::move
本身不会做任何动作。
您可以将其视为将对象标记为可以移动的对象。
function_call_move
的签名是
void function_call_move( unique_ptr<int>&& ptr );
这意味着它只能接收可以从中移动的对象,正式名称为rvalues,并将其绑定到引用。将rvalue与rvalue引用相关联的行为也不会使原始对象的状态无效。
因此,除非function_call_move
实际上将ptr
移动到其中的std::unique_ptr
,否则您对function_call_move(std::move(intptr));
的调用不会使intptr
无效,您的使用将会是完全没问题。