为什么在这种情况下不调用赋值运算符而支持复制构造函数?

nck*_*ner 2 c++ oop

从复制构造函数的维基百科页面:

X a = X();     

// valid given X(const X& copy_from_me) but not valid given X(X& copy_from_me)
// because the second wants a non-const X&
// to create a, the compiler first creates a temporary by invoking the default constructor
// of X, then uses the copy constructor to initialize as a copy of that temporary. 
// For some compilers both versions actually work but this behaviour should not be relied 
// upon because it's non-standard.
Run Code Online (Sandbox Code Playgroud)

特别是部分:

"编译器首先通过调用X的默认构造函数创建一个临时文件,然后使用复制构造函数初始化为该临时文件的副本."

我的问题是(假设这是正确的)为什么会这样?从代码中,我猜想编译器在构造X之后会使用赋值运算符.

我猜它是因为赋值发生在与初始化相同的表达式中?

另外,使用这个公式的原因是什么,而不仅仅是正常的初始化X a;或者你想要复制X a(b);

Pet*_*ker 7

因为代码正在构造一个对象.这里的=符号是初始化,而不是分配.您只能分配给现有对象,而不能分配给正在构建的对象.