C++ 移动语义行为异常
在以下代码中,C++ 移动语义行为异常,c++,c++11,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); } void条(std::shared_ptr&&value){ } void foo(){ 自动ptr=std:
foo
中的断言失败:
void bar (std::shared_ptr<int> && value) {
}
void foo () {
auto ptr = std::make_shared<int>(5);
bar(std::move(ptr));
assert(ptr == nullptr);
}
void条(std::shared_ptr&&value){
}
void foo(){
自动ptr=std::使_共享(5);
酒吧(标准::移动(ptr));
断言(ptr==nullptr);
}
调用bar
后,共享指针仍然指向值5。我希望对bar
的调用使用移动语义,使ptr
null
我的理解中的缺陷在哪里?执行实际移动后,指针将变为空<代码>标准::移动本身不会移动任何东西。它只允许将命名对象
ptr
传递给右值引用函数
由于实际上没有在该函数内部(或任何其他地方)移动任何对象,因此指针将保持不变
这样做(例如)
void条(std::shared_ptr&&value){
std::shared_ptr另一个_ptr(std::move(value));
}
您将看到原始指针移动。本质上,
std::move()
只是一个强制转换
更改bar()
以查看所需的结果
void bar (std::shared_ptr<int> && value)
{
std::shared_ptr<int> v{std::move(value)};
}
void条(std::shared_ptr&&value)
{
std::shared_ptr v{std::move(value)};
}
您希望它准确地移动到哪里?std::move()
声明:templateconstepr typename std::remove\u reference::type&&move(T&&T)代码>返回值:static_cast(t)
使用完美转发按引用或右值引用获取t
,并将其强制转换为右值引用。
void bar (std::shared_ptr<int> && value)
{
std::shared_ptr<int> v{std::move(value)};
}