c – 为什么不调用Copy构造函数将临时对象复制到新定义的对象

#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”规则的唯一例外,通常会限制编译器可以对程序执行的转换(优化),以保持其可观察行为.

请注意,上述机制称为复制elision – 即使它实际上是正在被删除的移动构造函数调用.

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...