移动语义意外行为

时间:2017-02-03 18:46:39

标签: c++ c++11

在以下代码中,foo中的断言失败:

void bar (std::shared_ptr<int> && value) {
}

void foo () {
    auto ptr = std::make_shared<int>(5);
    bar(std::move(ptr));
    assert(ptr == nullptr);
}

在调用bar后,共享指针仍然指向值5。我希望对bar的调用使用移动语义,使ptr为空。

我理解的缺陷在哪里?

2 个答案:

答案 0 :(得分:8)

基本上,std::move()只是演员。

更改bar()以查看您想要的结果。

void bar (std::shared_ptr<int> && value)
{
   std::shared_ptr<int> v{std::move(value)};
}

答案 1 :(得分:5)

执行实际移动后,指针将变为null。 std::move本身不会移动任何东西。它只是可以将命名的对象ptr传递给rvalue-reference-expecting函数。

由于你实际上没有在该函数内(或其他任何地方)移动任何东西,因此指针保持不动 - 来自。

这样做(例如)

void bar (std::shared_ptr<int> && value) {
  std::shared_ptr<int> another_ptr(std::move(value));
}

你会看到原来的指针移动了。