微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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数组,你得到一堆副本而不是一堆移动.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐