为什么移动const对象有效?

LxL*_*LxL 7 c++ move move-semantics c++11

我有一个简单的代码:

const std::vector<int> data = {1,2,3};
std::vector<int> data_moved=std::move(data);
for(auto& i:data)
    cout<<i;//output is 123
Run Code Online (Sandbox Code Playgroud)

它编译没有任何错误或警告!

似乎data 仍然有它的价值!

移动const值似乎不正确,因为我们无法修改const对象那么代码是如何编译的?

Lig*_*ica 9

你什么都没动.

std::move真是命名不好:它不会强迫一招; 它只返回一个右值.它是由编译器来决定哪个构造函数std::vector<int>调用,并认为那是什么决定了你是否得到一个举动.

如果由于目标的移动构造函数不匹配而无法移动容器,则将通过基本重载规则使用复制构造函数.

#include <iostream>

struct T
{
    T() = default;
    T(const T&) { std::cout << "copy ctor\n"; }
    T(T&&)      { std::cout << "move ctor\n"; }
};

int main()
{
    T a;
    T b = std::move(a);   // "move ctor"

    const T c;
    T d = std::move(c);   // "copy ctor" - `const T&&` only matches copy ctor



    // (shut up GCC)
    (void) b;
    (void) d;
}
Run Code Online (Sandbox Code Playgroud)

(现场演示)

它以这种方式设计(const T&&能够绑定const T&)至少部分是因为移动旨在尽力而为,这样您就不必在这种情况下与编译器错误作斗争.