c – 为什么在初始化列表中启动向量时没有移动构造(通过隐式构造函数)

前端之家收集整理的这篇文章主要介绍了c – 为什么在初始化列表中启动向量时没有移动构造(通过隐式构造函数)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
为了演示移动语义,我使用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;
  }
};

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

随着输出

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

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

Live demo

解决方法

I thought I had an initializer list of integers,but I’m now wondering if what I have in between is an initializer list of Cs,which can’t be moved from (as its const). Is this a correct interpretation?

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

猜你在找的C&C++相关文章