为什么在传递给另一个对象时调用const对象上的std :: move调用复制构造函数? [英] Why does calling std::move on a const object call the copy constructor when passed to another object?
问题描述
为什么在传递给另一个对象时,调用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:36: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
当然,我期望它失败,因为我们不能移动 调用 显式地 结果是有意义的,因为移动构造是一种操作,从源对象窃取资源,从而改变它,所以你不能这样做到一个 Why does calling std::move on a fails to compile with the message: Certainly, I expect it to fail because we can't move a The type of the result of calling Explicitly 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对象上的std :: move调用复制构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! const
值。同时,我不明白代码在尝试调用复制构造函数之前所采用的路由。意思是,我知道 std :: move
将元素转换为x值,但我不知道如何处理之后相对于
std的结果类型: :move
与 T const
参数是 T const&&
到 T&&&
参数。下一个最佳匹配是您的副本构造函数,它被删除,因此会出错。
delete
并不意味着它不能用于重载解析,但是如果它确实是通过重载解析选择的最可行的候选者,则它是编译器错误。
const
对象简单地调用 std :: move
。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));
}
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
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
.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.delete
ing 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.const
object simply by calling std::move
.