class Args {}; class MyClass { public: MyClass(Args& a) {} MyClass(MyClass &&) = delete; }; int main() { Args a; MyClass c1 = MyClass(a); MyClass c2 = a; MyClass c3(a); return 0; }
这不会编译,因为对象c1和c2的构造似乎涉及类的移动构造函数:
错误:使用已删除的函数’MyClass :: MyClass(MyClass&&)’
似乎编译器想要创建临时对象,然后将它们移动到c1和c2.为什么会这样?不应该所有三个语句都只调用MyClass(Args& a)构造函数吗?
解决方法
Under the following circumstances,the compilers are permitted,but not required to omit the copy- and move- (since C++11) construction of class objects even if the copy/move (since C++11) constructor and the destructor have observable side-effects. This is an optimization: even when it takes place and the copy-/move-constructor is not called,it still must be present and accessible (as if no optimization happened at all),otherwise the program is ill-formed.
从C 17开始:
They need not be present or accessible,as the language rules ensure that no copy/move operation takes place,even conceptually.
原文地址:https://www.jb51.cc/c/112969.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。