简体   繁体   English

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

[英]C++: “T a = b” — copy constructor or assignment operator?

Assume T is a C++ class, and if I do T a = b; 假设T是一个C ++类,如果我做T a = b; , is the copy constructor or assignment operator called? ,是复制构造函数还是赋值运算符?

My current experiment shows the copy constructor is called, but do not understand why. 我当前的实验显示复制构造函数被调用,但不明白为什么。

#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

Thanks! 谢谢!

The copy constructor is called because 调用复制构造函数是因为

T a = b;

has the same effect as 具有相同的效果

T a(b);

It's an initialization, not an assignment. 这是一个初始化,而不是一个任务。 Long story short, it's just how the language works. 长话短说,这就是语言的运作方式。

...

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

...

vs VS

...

T a;   // Default constructor is called

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

...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM