移动,好吗?

时间:2014-05-06 15:48:49

标签: c++11

让我们看看这个片段,正如预期的那样,我得到了In&& amp;打印。但是,如果我写了S z(x + y),我没有得到“在移动中”的调用,而不是z = x + y。相反,临时创建的内部运算符+似乎是z。也许编译器正在优化它,但我不太明白。

#include <algorithm>
#include <iostream>
using namespace std;

struct S {
  S(int N1) : N(N1) {
    cout << "In orig " << N << "\n";
  }

  S(S& s) {
    N = s.N;
    cout << "In copy\n";
  }

  S(S&& s) {
    N = s.N;
    cout << "In move\n";
  }

  S const & operator=(S&& s) {
    cout << "In &&\n";
  }

  S operator+(S const & s) {
    cout << "In +\n";
    return S(N + s.N);
  }

  int N;
};

int main()
{
  S x(33), y(44);
  S z = 99; // instead of this line and next try S z(x + y); --> no move constructor??
  z = (x + y);
}

0 个答案:

没有答案