How the copy operator recognizes its constructor

In the following code, when the operator X loc2 = loc; , the compiler recognizes that the constructor below should start, and then it starts.
X(const X& x) { val = x.val; out("X(X&)"); }

I know that a constructor is considered a copy constructor, but my question is how does the compiler know that this constructor has this statement? Is there any rule about what the structure of the copy constructor should look like so that it can be recognized and run when the copy statement is executed?

 #include "std_lib_facilities_4.h" using namespace std; struct X { int val; void out(const string& s) {cerr << this << " -> " << s << ": " << val << "\n\n"; } X(int v) { val = v; out("X(int)"); } X(const X& x) { val = x.val; out("X(X&)"); } // The copy constructor }; int main() { X loc(4); X loc2 = loc; // This statement char ch; cin>>ch; return 0; } 

std_lib_facilities here . The OS I use is Windows, and my compiler is Visual Studio.

+4
source share
1 answer

As long as the constructor takes one of the following forms, it will be automatically accepted at compilation as a copy constructor:

 X(const X& ); X(X&); X(volatile X& ); X(const volatile X& ); X(const X&, /*any number of arguments with default values*/); X(X&, /*any number of arguments with default values*/); 

Accept the first option if you do not have good reason to accept an alternative.

+5
source

All Articles