为什么不调用复制构造函数,但在此代码中调用缺省构造函数? [英] Why copy-constructor is not called but default constructor is invoked in this code?
问题描述
我理解当从已经存在的对象创建对象时,以及当函数按值返回对象时,将调用复制构造函数。那么为什么在下面的代码中,复制构造函数不是被调用,而是默认构造函数?
I have an understanding that copy constructor will be called when an object is created from an already existing object and also when a function returns object by value. So why in the below code the copy constructor is not called but the default constructor?
class A {
public:
A() { cout << "A" << endl; }
A(A &) { cout << "A&" << endl; }
A(const A &) { cout << "const A&" << endl; }
};
A fun() {
class A a;
return a;
}
int main() {
class A a = fun(); // output: A
}
推荐答案
回答:编译器优化。
-
首先,
a
函数直接在main
函数的范围内创建,以避免必须将局部参数复制(或在C ++ 11中移动)函数通过函数的返回。这是返回值优化。
First, the
a
object from your function is created directly in the scope of themain
function, in order to avoid having to copy (or move in C++11) the local parameter out of the scope of the function via the function's return. This is return value optimization.
然后,在main中,语句等价于 class A a = A()
,并且允许编译器创建 a
对象,而不从临时对象复制。这是复制。
Then, in main, the statement becomes equivalent to class A a = A()
and again the compiler is allowed to the create the a
object in place, without copying from a temporary object. This is copy elision.
这是允许的,即使复制构造函数旁路完全)具有副作用,如在您的示例中。
This is allowed even if the copy constructor (which is bypassed entirely) has side-effects, like in your example.
这篇关于为什么不调用复制构造函数,但在此代码中调用缺省构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!