我刚接触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
。然而,在函数调用中使用 std::move
时,比如在函数 unique_ptr_function_call_move()
中,intptr
仍然拥有其所指向的对象的所有权。当我们将一个 std::move(unique_ptr)
传递到一个函数中时,具体发生了什么呢?谢谢。
std::move
并不会移动任何东西,它只是允许其他想要窃取对象内容的函数这样做。function_call_move
不是这样的一个函数。 - Igor Tandetnik=
操作进行所有权转移,而不是std::move
,我在这部分是正确的吗? - keelarstd::move
被命名为std::move
? - dyp