为什么在传递给另一个对象时调用const对象上的std :: move调用复制构造函数? [英] Why does calling std::move on a const object call the copy constructor when passed to another object?

查看:180
本文介绍了为什么在传递给另一个对象时调用const对象上的std :: move调用复制构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在传递给另一个对象时,调用std :: move在 const 对象上调用复制构造函数?具体来说,代码

  #include< iostream> 

struct Foo {
Foo()= default;
Foo(Foo&& x){std :: cout<< 移动<< std :: endl; }
Foo(Foo const& x)= delete;
};

int main(){
Foo const x; Foo y(std :: move(x));
}

无法使用以下消息进行编译:

  g ++ -std = c ++ 14 test07.cpp -o test07 
test07.cpp:在函数'int main()':
test07.cpp:10:3​​6:error:使用删除的函数'Foo :: Foo(const Foo&)'
Foo const x; Foo y(std :: move(x));
^
test07.cpp:6:5:注意:这里声明了
Foo(Foo const& x)= delete;
^
Makefile:2:目标'all'失败的食谱
make:*** [all]错误1

当然,我期望它失败,因为我们不能移动 const 值。同时,我不明白代码在尝试调用复制构造函数之前所采用的路由。意思是,我知道 std :: move 将元素转换为x值,但我不知道如何处理之后相对于

调用 std的结果类型: :move T const 参数是 T const&& T&&& 参数。下一个最佳匹配是您的副本构造函数,它被删除,因此会出错。



显式地 delete 并不意味着它不能用于重载解析,但是如果它确实是通过重载解析选择的最可行的候选者,则它是编译器错误。



结果是有意义的,因为移动构造是一种操作,从源对象窃取资源,从而改变它,所以你不能这样做到一个 const 对象简单地调用 std :: move


Why does calling std::move on a const object call the copy constructor when passed to another object? Specifically, the code

#include <iostream>

struct Foo {
    Foo() = default;
    Foo(Foo && x) { std::cout << "Move" << std::endl; }
    Foo(Foo const & x) = delete;
};

int main() {
    Foo const x; Foo y(std::move(x)); 
}

fails to compile with the message:

g++ -std=c++14 test07.cpp -o test07
test07.cpp: In function 'int main()':
test07.cpp:10:36: error: use of deleted function 'Foo::Foo(const Foo&)'
     Foo const x; Foo y(std::move(x)); 
                                    ^
test07.cpp:6:5: note: declared here
     Foo(Foo const & x) = delete;
     ^
Makefile:2: recipe for target 'all' failed
make: *** [all] Error 1

Certainly, I expect it to fail because we can't move a const value. At the same time, I don't understand the route that the code takes before it tries to call the copy constructor. Meaning, I know that std::move converts the element to an x-value, but I don't know how things proceed after that with respect to const.

解决方案

The type of the result of calling std::move with a T const argument is T const&&, which cannot bind to a T&& parameter. The next best match is your copy constructor, which is deleted, hence the error.

Explicitly deleteing a function doesn't mean it is not available for overload resolution, but that if it is indeed the most viable candidate selected by overload resolution, then it's a compiler error.

The result makes sense because a move construction is an operation that steals resources from the source object, thus mutating it, so you shouldn't be able to do that to a const object simply by calling std::move.

这篇关于为什么在传递给另一个对象时调用const对象上的std :: move调用复制构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆