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

c – 为什么移动构造函数涉及到此处

发布时间:2020-12-16 06:01:18 所属栏目:百科 来源:网络整理
导读:我有这段C代码: 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的构造似乎涉及类的移动构
我有这段C代码:
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)构造函数吗?

另一方面,如果我创建移动构造函数,程序编译正常,移动构造函数永远不会被调用!

解决方法

见 copy elision:

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.

(编辑:李大同)

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

    推荐文章
      热点阅读