【发布时间】:2014-02-27 13:31:16
【问题描述】:
我是 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不是这样的功能。 -
std::move 从 unique_ptr 创建一个 RValue 引用。 function_call_move 采用 RValue 引用,但在使用 RValue 引用赋值运算符或构造函数来窃取 unique_ptr 的信息之前,它不会受到损害。本质上,仅仅因为你可以抢劫并窃取它的信息并不意味着你必须这样做。
-
@Dan:非常感谢您的评论。所以所有权转移是
=操作,而不是std::move,我在这部分是正确的吗?
标签: c++ c++11 move smart-pointers