C ++:“T a = b” - 复制构造函数或赋值运算符?

时间:2014-11-13 21:05:03

标签: c++ copy-constructor assignment-operator

假设T是一个C ++类,如果我T a = b;,是复制构造函数还是赋值运算符?

我当前的实验显示复制构造函数被调用,但不明白为什么。

#include <iostream>
using namespace std;

class T {
 public:
  // Default constructor.
  T() : x("Default constructor") { }
  // Copy constructor.
  T(const T&) : x("Copy constructor") { }
  // Assignment operator.
  T& operator=(const T&) { x = "Assignment operator"; }
  string x;
};

int main() {
  T a;
  T b = a;
  cout << "T b = a; " << b.x << "\n";
  b = a;
  cout << "b = a; " << b.x << "\n";
  return 0;
}

$ g++ test.cc
$ ./a.out
T b = a; Copy constructor
b = a; Assignment operator

谢谢!

2 个答案:

答案 0 :(得分:6)

调用复制构造函数是因为

T a = b;

具有相同的效果
T a(b);

这是初始化,而不是作业。长话短说,这就是语言的运作方式。

答案 1 :(得分:2)

...

// The variable a does not exist before this point, therefore it is *conststructed*
T a = b; // Copy constructor is called

...

VS

...

T a;   // Default constructor is called

// a already exists, so assignment is used here
a = b; // assignment operator is called

...