应该std :: move drop constness?

时间:2013-02-21 13:33:11

标签: c++ c++11 const move-semantics

以下代码在MSVC2010上编译并运行,是吗?

const std::string s = "foo";
std::string s2(std::move(s));

我可以看出为什么这可能不会破坏任何东西,因为如果我采用s的内部结构我必须知道没有人会使用它所以我不得不放弃const。然而,编译器在ROM(在嵌入式应用程序中)实现const对象的位置呢?那么此举会变成副本吗?或者MSVC应该给我一个错误?

2 个答案:

答案 0 :(得分:30)

我认为std::move(T const&)只会返回T const &&。这意味着,它实际上不会被移动(因为移动赋值运算符/构造函数与param类型不匹配)。

结果是,T const&的构造函数与 lvalue 变量类型T const &&)匹配,因此,此举降级为副本。

答案 1 :(得分:23)

这与

没什么区别
const std::string f() { return "foo"; }
std::string s2 = f();

这曾经一度推荐使用C ++ 03,并且委员会在引入右值引用时没有打破这段代码。它只是降级为副本。