了解std :: move和unique_ptr

时间:2014-02-03 21:16:09

标签: c++ c++11 move smart-pointers

我是c ++ 11的新手并尝试理解std::moveunique_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()中,intptr2intptr之后获得std::move的所有权,因此我们无法再使用intptr。但是,在unique_ptr_function_call_move()中,在函数调用中使用std::move时,intptr仍然拥有其指向实例的所有权。当我们将std::move(unique_ptr)传递给函数时,我能知道到底发生了什么吗?谢谢。

1 个答案:

答案 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无效,您的使用将会是完全没问题。