Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/150.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 移动语义行为异常_C++_C++11 - Fatal编程技术网

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)};
}