#include <iostream> using namespace std; class Y { public: Y(int ) { cout << "Y(int)\n"; } Y(const Y&) { cout << " Y(const Y&)\n"; } }; int main() { Y obj1 = 2; // Line 1 }
输出:Y(int)
预期输出:Y(int)
Y(const Y&)
问题>基于我的理解,第1行将首先创建一个临时对象Y(2),然后将临时对象分配给obj1.因此,我期望Y(int)和Y(const Y&)都被调用.但是,vs2010的输出仅报告第一个(即Y(int)).为什么?
解决方法
Why?
因为在某些条件下(由C 11标准的12.8 / 31号指定)调用复制构造函数或移动构造函数即使这些特殊函数(或析构函数)也有副作用:
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— […]
这是所谓的“as-if”规则的唯一例外,通常会限制编译器可以对程序执行的转换(优化),以保持其可观察行为.