【问题标题】:Explicit move constructor needed in container?容器中需要显式移动构造函数?
【发布时间】:2017-06-15 17:11:02
【问题描述】:

我有一个模板化的容器类:

 template<class Stuff>
 class Bag{
     private:
        std::vector<Stuff> mData;
 };

我想做

  void InPlace(Bag<Array>& Left){
      Bag<Array> temp;
      Transform(Left, temp); //fills temp with desirable output
      Left = std::move(temp);
  }

假设 Array 具有用户定义的移动语义,但 Bag 没有。在这种情况下,mData 会被移动还是复制?

【问题讨论】:

  • 不错,已修复

标签: c++ c++11


【解决方案1】:

它将被移动,而不是复制。

我建议看下图:



这清楚地表明,只要用户没有定义他/她自己的,编译器就会隐式生成一个移动构造函数:

  • 析构函数
  • 复制构造函数
  • 复制分配
  • 移动作业

由于您的类没有这些用户定义的构造函数,编译器生成的移动构造函数将被调用,该构造函数将移动mData。

【讨论】:

猜你喜欢
  • 2017-11-18
  • 2015-03-21
  • 2014-03-19
  • 2011-10-09
  • 2019-04-09
  • 1970-01-01
  • 1970-01-01
  • 2015-08-04
相关资源
最近更新 更多