在以下代码中,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
为空。
我理解的缺陷在哪里?
答案 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));
}
你会看到原来的指针移动了。