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

c – 为什么不调用Copy构造函数将临时对象复制到新定义的对象,第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; /
#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 – 为什么不调用Copy构造函数将临时对象复制到新定义的对象全部内容,希望文章能够帮你解决c – 为什么不调用Copy构造函数将临时对象复制到新定义的对象所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1251294.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-07
下一篇 2022-06-07

发表评论

登录后才能评论

评论列表(0条)

保存