复制语句如何识别其构造函数

Fra*_*nky 4 c++ copy-constructor

X loc2 = loc;执行语句时,下面的代码中,编译器识别出下​​面的构造函数应该运行,然后运行它.
X(const X& x) { val = x.val; out("X(X&)"); }

我知道构造函数被认为是一个复制构造函数,但我的问题是编译器如何知道构造函数是该语句的?有没有关于复制构造函数的结构应该如何在执行复制语句时被识别和运行的规则?

#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;
}
Run Code Online (Sandbox Code Playgroud)

std_lib_facilities就在这里.我使用的操作系统是Windows,我的编译器是Visual Studio.

Bat*_*eba 6

只要构造函数具有以下形式之一,它将在编译时自动采用为复制构造函数:

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*/);
Run Code Online (Sandbox Code Playgroud)

采用第一个,除非你有充分的理由采用替代方案.