从初始化列表中启动向量时,为什么不使用移动构造(通过隐式构造函数)

Joh*_*erg 6 c++ initializer-list move-semantics c++14

为了演示移动语义,我使用int中的隐式构造函数编写了以下示例代码.

struct C {
  int i_=0;
  C() {}
  C(int i) : i_( i ) {}
  C( const C& other) :i_(other.i_) {
    std::cout << "A copy construction was made." << i_<<std::endl;
  }
  C& operator=( const C& other) {
    i_= other.i_ ;
    std::cout << "A copy assign was made."<< i_<<std::endl;
    return *this;
  }
  C( C&& other ) noexcept :i_( std::move(other.i_)) {
    std::cout << "A move construction was made." << i_ << std::endl;
  }
  C& operator=( C&& other ) noexcept {
    i_ = std::move(other.i_);
    std::cout << "A move assign was made." << i_ << std::endl;
    return *this;
  }
};
Run Code Online (Sandbox Code Playgroud)

auto vec2 = std::vector<C>{1,2,3,4,5};
cout << "reversing\n";
std::reverse(vec2.begin(),vec2.end());
Run Code Online (Sandbox Code Playgroud)

随着输出

A copy construction was made.1
A copy construction was made.2
A copy construction was made.3
A copy construction was made.4
A copy construction was made.5
reversing
A move construction was made.1
A move assign was made.5
A move assign was made.1
A move construction was made.2
A move assign was made.4
A move assign was made.2
Run Code Online (Sandbox Code Playgroud)

现在,反过来显示了2个两个交换(每个交换使用一个移动分配和两个移动构造),但为什么C从初始化列表创建的临时对象无法移动?我以为我有一个整数的初始化列表,但我现在想知道我之间是否有一个Cs的初始化列表,它不能被移动(作为它的const).这是正确的解释吗?- 这是怎么回事?

现场演示

Bar*_*rry 9

我以为我有一个整数的初始化列表,但我现在想知道我之间是否有一个Cs的初始化列表,它不能被移动(作为它的const).这是正确的解释吗?

这是对的.vector<C>没有initializer_list<int>构造函数甚至是initializer_list<T>某个模板参数的构造函数T.它所拥有的是一个initializer_list<C>构造函数 - 它是从你传入的所有int构建的.由于initializer_list是一个const数组的支持,你得到一堆副本而不是一堆移动.