#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”规则的唯一例外,通常会限制编译器可以对程序执行的转换(优化),以保持其可观察行为.
原文地址:https://www.jb51.cc/c/113254.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。