默认移动构造函数与默认副本构造函数与默认赋值运算符 [英] Default move constructor vs. Default copy constructor vs. Default assignment operator

查看:77
本文介绍了默认移动构造函数与默认副本构造函数与默认赋值运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么C ++编译器对自动生成的移动构造函数比对自动生成的复制构造函数或赋值运算符有更多的限制?

Why does C++ compiler have more restriction on automatically generated move constructors than on automatically generated copy constructor or assignment operator ?

仅当用户具有没有定义任何内容(即:构造函数,复制,赋值,析构函数。)

Automatically generated move constructors are generated only if user has defined nothing (i.e: constructor, copy, assignment, destructor..)

仅当用户未分别定义复制构造函数或赋值运算符时,才会生成复制构造函数或赋值运算符。

Copy constructor or assignment operator are generated only if user has not defined respectively copy constructor or assignment operator.

我想知道为什么会有所不同。

I wonder why the difference.

推荐答案

我相信向后兼容在这里起着很大的作用。如果用户定义了三个规则中的任何一个功能(复制ctor,复制分配op,dtor),则可以假定该类在做一些内部资源管理。隐式定义move构造函数可能会突然使类在C ++ 11下编译时无效。

I believe backwards compatibility plays a big part here. If the user defines any of the "Rule of three" functions (copy ctor, copy assignment op, dtor), it can be assumed the class does some internal resource management. Implicitly defining a move constructor could suddenly make the class invalid when compiled under C++11.

请考虑以下示例:

class Res
{
  int *data;

public:
  Res() : data(new int) {}

  Res(const Res &arg) : data(new int(*arg.data)) {}

  ~Res() { delete data; }
};

现在,如果为此类生成了默认的move构造函数,则其调用将导致双重删除 data

Now if a default move constructor was generated for this class, its invocation would lead to a double deletion of data.

至于移动赋值运算符可防止默认的移动构造函数定义:如果移动赋值运算符执行其他操作比默认移动构造器更难使用默认的移动构造器。实际上,这就是三个规则 /五个规则。

As for the move assignment operator preventing default move constructor definitions: if the move assignment operator does something other than default one, it would most likely be wrong to use the default move constructor. That's just the "Rule of three"/"Rule of five" in effect.

这篇关于默认移动构造函数与默认副本构造函数与默认赋值运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆