移动构造函数和赋值运算符与复制省略

时间:2019-05-12 22:50:43

标签: c++ c++11 move-semantics move-constructor copy-elision

相关问题:

我发布这个问题是因为,这种移动语义确实让我感到困惑。最初,它们对我来说似乎很清楚,但是当我尝试向自己演示这些功能的使用时,我意识到也许我误解了一些东西。

我试图通过移动语义将以下文件安排为类似于矢量的类的简单实现(实际上,main函数也在那里,还有一个免费的功能使打印到屏幕更容易...)。这并不是真正的 minimum 工作示例,但是它在屏幕上产生的输出是相当可读的,恕我直言。

不过,如果您觉得最好将其缩小,请建议我该怎么做。

无论如何下面的代码,

#include<iostream>
using namespace std;

int counter = 0; // to keep count of the created objects

class X {
  private:
    int id = 0; // hopefully unique identifyier
    int n = 0;
    int * p;
  public:
    // special member functions (ctor, dtor, ...)
    X()           : id(counter++), n(0),   p(NULL)       { cout << "default ctor (id " << id << ")\n"; }
    X(int n)      : id(counter++), n(n),   p(new int[n]) { cout << "param ctor (id " << id << ")\n"; };
    X(const X& x) : id(counter++), n(x.n), p(new int[n]) {
      cout << "copy ctor (id " << id << ") (allocating and copying " << n << " ints)\n";
      for (int i = 0; i < n; ++i) {
        p[i] = x.p[i];
      }
    };
    X(X&& x)      : id(counter++), n(x.n), p(x.p) {
      cout << "move ctor (id " << id << ")\n";
      x.p = NULL;
      x.n = 0;
    };
    X& operator=(const X& x) {
      cout << "copy assignment (";
      if (n < x.size() && n > 0) {
        cout << "deleting, ";
        delete [] p;
        n = 0;
      }
      if (n == 0) {
        cout << "allocating, and ";
        p = new int[n];
      }
      n = x.size();
      cout << "copying " << n << " values)";
      for (int i = 0; i < n; ++i) {
        p[i] = x.p[i];
      }
      cout << endl;
      return *this;
    };
    X& operator=(X&& x) {
      this->n = x.n;
      this->p = x.p;
      x.p = NULL;
      x.n = 0;
      cout << "move assignment (\"moving\" " << this->n << " values)\n";
      return *this;
    };
    ~X() {
      cout << "dtor on id " << id << " (array of size " << n << ": " << *this << ")\n";
      delete [] p;
      n = 0;
    }
    // getters/setters
    int size() const { return n; }

    // operators
    int& operator[](int i) const { return p[i]; };
    X operator+(const X& x2) const {
      cout << "operator+\n";
      int n = min(x2.size(), this->size());
      X t(n);
      for (int i = 0; i < n; ++i) {
        t.p[i] = this->p[i] + x2.p[i];
      }
      return t;
    };

    // friend function to slim down the cout lines
    friend ostream& operator<<(ostream&, const X&);
};

int main() {
    X x0;
  X x1(5);
  X x2(5);
  x1[2] = 3;
  x2[3] = 4;
  cout << "\nx0 = x1 + x2;\n";
  x0 = x1 + x2;
  cout << "\nX x4(x1 + x2);\n";
  X x4(x1 + x2);
  cout << x4 << endl;
  cout << '\n';
}

// function to slim down the cout lines
ostream& operator<<(ostream& os, const X& x) {
  os << '[';
  for (int i = 0; i < x.size() - 1; ++i) {
    os << x.p[i] << ',';
  }
  if (x.size() > 0) {
    os << x.p[x.size() - 1];
  }
  return os << ']';
}

当我编译并运行它时

$ clear && g++ moves.cpp && ./a.out

输出如下(手动添加#条评论)

default ctor (id 0)
param ctor (id 1)
param ctor (id 2)

x0 = x1 + x2;
operator+
param ctor (id 3)
move assignment ("moving" 5 values)
dtor on id 3 (array of size 0: [])

X x4(x1 + x2);
operator+
param ctor (id 4)
[0,0,3,4,0]

dtor on id 4 (array of size 5: [0,0,3,4,0])
dtor on id 2 (array of size 5: [0,0,0,4,0])
dtor on id 1 (array of size 5: [0,0,3,0,0])
dtor on id 0 (array of size 5: [0,0,3,4,0])

从输出的第一部分开始,我想我确实演示了移动分配运算符的预期用法。在这方面我是对的吗? (从下一个输出中,我似乎不是,但是我不确定。)

在这一点上,如果我认为复制省略阻止了对复制ctor的调用是正确的,那么我自然会想到一个问题(and not only me, see OP's comment here):

不是基于x4x1 + x2的结果基于另一个临时对象(例如 X x4(x1 + x2);创建对象的情况)正是应该为其引入移动语义的一种?如果不是,那么显示移动ctor用法的基本示例是什么?

然后我读到可以通过添加适当的选项来防止复制省略。

的输出
clear && g++ -fno-elide-constructors moves.cpp && ./a.out 

但是,以下内容是

default ctor (id 0)
param ctor (id 1)
param ctor (id 2)

x0 = x1 + x2;
operator+
param ctor (id 3)
move ctor (id 4)
dtor on id 3 (array of size 0: [])
move assignment ("moving" 5 values)
dtor on id 4 (array of size 0: [])

X x4(x1 + x2);
operator+
param ctor (id 5)
move ctor (id 6)
dtor on id 5 (array of size 0: [])
move ctor (id 7)
dtor on id 6 (array of size 0: [])
[0,0,3,4,0]

dtor on id 7 (array of size 5: [0,0,3,4,0])
dtor on id 2 (array of size 5: [0,0,0,4,0])
dtor on id 1 (array of size 5: [0,0,3,0,0])
dtor on id 0 (array of size 5: [0,0,3,4,0])
+enrico:CSGuild$ 

现在看起来像是我期望的对移动ctor的调用,但是该调用和对移动分配的调用都在前面分别有另一个对移动ctor的调用。

为什么会这样?我是否完全误解了移动语义的含义?

1 个答案:

答案 0 :(得分:3)

您似乎在这里有两个问题:

  • 为什么没有为X x4(x1 + x2)调用move构造函数?
  • 为什么在禁用复制省略时,move构造函数被调用了两次?

第一个问题

  

不是那种情况(X x4(x1 + x2);)正是这种情况   应该在哪里引入语义?

嗯,不。为了使用移动语义,您实际上建议我们选择在X构造一个operator+,然后将其移动到结果{{1 }} ,相比之下,复制复制的构造x4 期间就位的最终结果(x4)效率低下。

第二个问题

已禁用复制删除功能,为什么在operator+期间看到两次对move构造函数的调用?考虑到这里有三个作用域:

  1. X x4(x1 + x2)范围,我们在其中构造operator+并将其返回;
  2. 我们称为X的{​​{1}}范围;
  3. 我们从main构建X x4(x1 + x2)的{​​{1}};

然后,在没有省略的情况下,编译器为:

  • 将结果从X constructor移至X(移至x1 + x2);和
  • operator+的内容移至main