理解 std::move 和 unique_ptr

kee*_*lar 3 c++ smart-pointers move c++11

我是 c++11 的新手,并试图理解std::moveand 的含义unique_ptr并编写了以下代码,我以两种不同的方式std::move在 aunique_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);
}
Run Code Online (Sandbox Code Playgroud)

unique_ptr_plain_move(),intptr2拥有intptrafter的所有权,std::move因此我们不能再使用intptr. 但是,在unique_ptr_function_call_move()std::move在函数调用中使用时,intptr仍然拥有其指向实例的所有权。当我们将 a 传递std::move(unique_ptr)给一个函数时,我能知道到底发生了什么吗?谢谢你。

Tia*_*mes 5

这里的关键概念是它std::move本身不会做任何移动。您可以将其视为将对象标记为可以从中移动的对象。

的签名function_call_move

void function_call_move( unique_ptr<int>&& ptr );
Run Code Online (Sandbox Code Playgroud)

这意味着它只能接收可以从中移动的对象,正式称为右值,并将其绑定到引用。将右值关联到右值引用的行为也不会使原始对象的状态无效。

因此,除非function_call_move实际移动ptr到其中的另一个,否则std::unique_ptr您的调用function_call_move(std::move(intptr));不会无效intptr并且您的使用将完全正常。