当我阅读有关复制初始化与直接初始化的文章时 here .复制构造函数应该调用复制初始化。为什么这里复制构造函数不调用?
#include <iostream>
using namespace std;
class A{};
class B{
public:
B(const A &a){cout << "B construct from A" << endl;}
B(const B &b){cout << "B copy constructor" << endl;}
};
int main(){
A a;
B b = a;
return 0;
}
最佳答案
这是复制省略引用 1:。
编译器可以通过创建内联对象来优化生成临时对象时的复制构造函数调用,这是 C++ 标准明确允许的。
标准中也通过示例很好地证明了这一点:
C++03 标准 12.2 临时对象 [class.temporary]
第 2 段:
[Example:
class X {
// ...
public:
// ...
X(int);
X(const X&);
˜X();
};
X f(X);
void g()
{
X a(1);
X b = f(X(2));
a = f(a);
}
Here, an implementation might use a temporary in which to construct
X(2)
before passing it tof()
using X’s copy-constructor; alternatively,X(2)
might be constructed in the space used to hold the argument. Also, a temporary might be used to hold the result off(X(2))
before copying it to`b using
X’s copyconstructor; alternatively,
f()’s result might be constructed in b. On the other hand, the expression
a=f(a)requires a temporary for either the argument a or the result of
f(a)to avoid undesired aliasing of
a`. ]
引用 1:
C++03 12.8 复制类对象[class.copy]
第 12 段:
When certain criteria are met, an implementation is allowed to omit the copy construction of a class object, even if the copy constructor and/or destructor for the object have side effects.....
关于c++ - 复制构造函数不调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12686099/