当我读到复制初始化与直接初始化时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;
}
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.
标准中也通过示例很好地证明了这一点:
C++03 标准 12.2 临时对象 [class.temporary]
Para 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(2)
在将其传递给之前f()
使用 X 的复制构造函数;或者,X(2)
可以在用于保存论证的空间中构建。此外,可以使用临时来保存结果f(X(2))
在将其复制到之前`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`. ]
Ref 1:
C++03 12.8 Copying class objects [class.copy]
Para 12:
当满足某些条件时,允许实现省略类对象的复制构造,即使对象的复制构造函数和/或析构函数有副作用......
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)