复制构造函数不调用 [英] Copy constructor not calling
问题描述
当我阅读有关复制初始化与直接初始化这里。复制构造函数应调用复制初始化。为什么这里拷贝构造函数不调用?
When I read about copy initializing vs direct initializing here. copy constructor should call in copy initializing. why here copy constructor not calling?
#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;
}
推荐答案
Elision Ref 1:。
在生成临时表时复制构造函数调用可能由编译器通过在线创建对象进行优化,并且由C ++标准明确允许。
This is Copy ElisionRef 1:.
Copy constructor calls while generating temporaries might be optimized by the compiler by creating objects inline and it is explicitly allowed by the C++ Standard.
这也很好地在标准中演示了一个例子:
This is nicely demonstrated in the standard with an example as well:
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);
}
它使用X的复制构造函数将它传递给
f()
之前构造X(2)
或者,可以在用于保存参数的空间中构造X(2)
。此外,在将f(X(2))
的结果复制到`b之前,可以使用临时变量来保存结果
X的copyconstructor;或者,可以在b中构造
f()的结果。另一方面,表达式
a = f(a)需要一个临时的参数a或
f(a)以避免不必要的别名
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.....
这篇关于复制构造函数不调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!