C++ 理解std::移动和唯一\u ptr
我是c++11新手,试图理解C++ 理解std::移动和唯一\u ptr,c++,c++11,move,smart-pointers,C++,C++11,Move,Smart Pointers,我是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(
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);
}
void unique\u ptr\u plain\u move(){
唯一的(新整数(10));
唯一的\u ptr intptr2;
printf(“*intptr=%d\n”,*intptr);
intptr2=std::move(intptr);
printf(“*intptr2=%d\n”,*intptr2);
//正如所料,在这里崩溃,因为我们已经转移了intptr的所有权。
printf(“*intptr=%d\n”,*intptr);
}
/////////////////////////////////////////////
无效函数\u调用\u移动(唯一\u ptr&&intptr){
printf(“[func]*intptr=%d\n”,*intptr);
}
无效唯一\u ptr\u函数\u调用\u移动(){
唯一的(新整数(10));
printf(“*intptr=%d\n”,*intptr);
函数调用移动(std::move(intptr));
//这不会崩溃,intptr仍然拥有其指向实例的所有权。。。。
printf(“*intptr=%d\n”,*intptr);
}
在
unique_ptr_plain_move()
中,intptr2
在std::move
之后拥有intptr
的所有权,因此我们不能再使用intptr
。但是,在unique\u ptr\u function\u call\u move()
中,在函数调用中使用std::move
时,intptr
仍拥有其指向实例的所有权。我能知道当我们将std::move(unique_ptr)
传递给函数时到底发生了什么吗?谢谢。这里的关键概念是,std::move
本身不会做任何移动。
可以将其视为将对象标记为可以从中移动的对象
函数调用移动的签名为
void function_call_move( unique_ptr<int>&& ptr );
void函数\u调用\u移动(唯一\u ptr&&ptr);
这意味着它只能接收可以从中移动的对象(正式称为右值),并将其绑定到引用。将右值关联到右值引用的行为也不会使原始对象的状态无效
因此,除非function\u call\u move
实际上将ptr
移动到另一个std::unique\u ptr
内部,否则您对function\u call\u move(std::move(intptr))的调用
不会使intptr
无效,您的使用也会很好。调用std::move
本身不会移动任何东西。它只允许其他想要窃取对象内容的函数这样做function\u call\u move
不是这样的函数。std::move从unique\u ptr创建一个右值引用。函数_call _move接受右值引用,但在使用右值引用赋值运算符或构造函数窃取唯一的_ptr信息之前,它不会受到损害。本质上,你可以抢劫它并窃取它的信息并不意味着你必须这么做。@Dan:非常感谢你的评论。因此,所有权转移的是=
操作,而不是std::move
,我在这一部分做得对吗?很抱歉,我没有在一开始就为函数调用移动提供签名,但我在观察到这一点后立即提供了签名。非常感谢您的详细回答!