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++类中,有6个默认成员函数: 构造函数 析构函数 拷贝...
#pragma once // 1. 设计一个不能被拷贝的类/* 解析:拷贝只会放生在两个场景中:拷贝构造函数以及赋值运...
C类型转换 C语言:显式和隐式类型转换 隐式类型转化:编译器在编译阶段自动进行,能转就转,不能转就编译...
//异常的概念/*抛出异常后必须要捕获,否则终止程序(到最外层后会交给main管理,main的行为就是终止) try...
#pragma once /*Smart pointer 智能指针;灵巧指针 智能指针三大件//1.RAII//2.像指针一样使用//3.拷贝问...
目录&lt;future&gt;future模板类成员函数:promise类promise的使用例程:packaged_task模板类例程...