有如下代码,为什么运行结果只调用了默认构造函数却没有调用拷贝构造函数,
A() 会生成一个临时地 A 对象, 将这个临时的对象作为 a 的初始值,不是应该调用拷贝构造函数吗?请指教
还有就是这种调用:
为什么什么输出也没有?
调用复制构造函数的3种情况:1.用一个类的对象去初始化另一个对象,如A a;A b=a;
2.如果某函数的形参是类对象,当调用函数时,实参与形参结合时,
3.函数的返回值是类对象,函数执行完返回给调用者
A a = A(); 这个是默认构造
A b = A(a); 这个是复制构造
先不说什么含义, 参数对不上没发现吗?
不知道什么原因在楼里回复不了。。。。
我看错了,抱歉
这里应该是编译器做的优化,先创建一个临时的(之前没用过)再复制构造被直接优化成了一步默认构造
用gcc -S看一下是不是编译器优化掉了。
In particular, C++ standard 2014 §12.8 para 31, defines cases when copy elision can be performed:
When certain criteria are met, an implementation is allowed to omit the copy/move construction of a class object, even if the constructor selected for the copy/move operation and/or the destructor for the object have side effects... This elision of copy/move operations, called copy elision, is permitted in the following circumstances (which may be combined to eliminate multiple copies):
when a temporary class object that has not been bound to a reference (12.2) would be copied/moved to a class object with the same cv-unqualified type, the copy/move operation can be omitted by constructing the temporary object directly into the target of the omitted copy/move.
赋值和拷贝不同,使用等号=的是赋值,以该类型作为构造函数参数是拷贝:
A a; // 默认构造函数
A b(a); // 拷贝构造函数
A c;
c = a; // 拷贝赋值运算符