【问题标题】:Understanding std::move and unique_ptr了解 std::move 和 unique_ptr
【发布时间】:2014-02-27 13:31:16
【问题描述】:

我是 c++11 的新手,并试图理解 std::moveunique_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() 中,intptr2std::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


【解决方案1】:

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

function_call_move 的签名是

void function_call_move( unique_ptr<int>&& ptr );

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

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

【讨论】:

  • 很抱歉,我一开始没有提供function_call_move的签名,但我在观察后立即提供了。非常感谢您的详细解答!
猜你喜欢
  • 1970-01-01
  • 2012-12-01
  • 2016-03-21
  • 1970-01-01
  • 2019-07-09
  • 2013-05-18
  • 2022-01-12
  • 1970-01-01
  • 2020-08-23
相关资源
最近更新 更多