加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 05:57:11 所属栏目:百科 来源:网络整理
导读:#include iostreamusing 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行将首先创建一个临时
#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 – 即使它实际上是正在被删除的移动构造函数的调用.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读