C ++: "T a = b" - copy constructor or assignment operator?

Suppose it Tis a C ++ class, and if I execute T a = b;, is it a copy constructor or an assignment operator called?

My current experiment shows that the copy constructor is being called, but I don’t 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

Thank!

+4
source share
2 answers

The copy constructor is called because

T a = b;

has the same effect as

T a(b);

This is initialization, not a task. In short, this is just how the language works.

+6
source
...

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

...

against

...

T a;   // Default constructor is called

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

...
+2
source

All Articles