编译器何时为类的特殊成员提供定义? [英] When does the compiler provide definitions for the special members of a class?

查看:21
本文介绍了编译器何时为类的特殊成员提供定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道当我定义一个空类并且根本不提供任何声明时,编译器将为默认和复制构造函数、析构函数和复制赋值运算符提供定义.

I know that when I define an empty class and provide no declarations at all, the compiler will provide definitions for the default and copy constructor, destructor and copy assignment operator.

这有什么规则?编译器什么时候提供复制构造函数?移动构造函数和移动赋值运算符呢?

What are the rules for that? When does the compiler not provide a, say, copy constructor? What about the move constructor and move assignment operator?

(例如:如果我的类具有像 int& 这样的引用成员,编译器将不会为任何赋值运算符提供定义.这种情况何时会发生?)

(Example: The compiler will not provide definitions for any assignment operator if my class has a reference member like int&. When else will something like this happen?)

推荐答案

在 C++11 中,它比隐式声明或不隐式声明更复杂.它们可以被隐式声明和默认,隐式声明和删除,或未声明.阅读this以区分后两种.以下信息不完全正确,因为它没有区分声明和删除与未申报.

In C++11 it's more complicated than implicitly declared or not. They can either be implicitly declared and defaulted, implicitly declared and deleted, or undeclared. Read this to distinguish the latter 2. The following information isn't entirely correct since it doesn't distinguish declared and deleted vs undeclared.

以下是正在进行的工作.(?) 表示我想澄清或量化声明.

The following is a work in progress. (?) indicates I would like to clarify or quantify the statement.

当用户没有显式声明它们时,实现会为某些类类型隐式声明这些成员函数:

The implementation will implicitly declare these member functions for some class types when the user does not explicitly declare them:

  • 默认构造函数
  • 复制构造函数
  • 复制赋值运算符
  • 移动构造函数
  • 移动赋值运算符
  • 析构函数
  • 用户声明的移动构造函数
  • 用户声明的移动赋值运算符
  • 右值引用类型的非静态数据成员
  • 具有非平凡复制构造函数的变体成员,并且是类似联合的类 (?)
  • 无法复制的类型(或其数组)的非静态数据成员
  • 没有可访问的复制构造函数的直接或虚拟基类

*如果类具有用户声明的复制赋值运算符或用户声明的析构函数 (?),则不推荐使用这种隐式声明

*Such an implicit declaration is deprecated if the class has a user-declared copy assignment operator or a user-declared destructor (?)

  • 用户声明的移动构造函数
  • 用户声明的移动赋值运算符
  • 具有非平凡复制赋值运算符的变体成员,并且是类似联合的类 (?)
  • const 非类类型(或其数组)的非静态数据成员
  • 引用类型的非静态数据成员
  • 具有不可访问的复制赋值运算符的非静态数据成员
  • 具有不可访问的复制赋值运算符的直接或虚拟基类

*如果类具有用户声明的复制构造函数或用户声明的析构函数 (?),则不推荐使用这种隐式声明

*Such implicit declaration is deprecated if the class has a user-declared copy constructor or a user-declared destructor (?)

  • 用户声明的复制构造函数
  • 用户声明的复制赋值运算符
  • 用户声明的移动赋值运算符
  • 用户声明的析构函数
  • 移动构造函数不会被隐式定义为已删除 (?)
  • 具有非平凡移动构造函数的变体成员,并且是类似联合的类 (?)
  • 不能移动的类型(或其数组)的非静态数据成员
  • 非静态数据成员或直接或虚拟基类,其类型没有移动构造函数且不可简单复制
  • 没有可访问的移动构造函数的直接或虚拟基类
  • 用户声明的复制构造函数
  • 用户声明的移动构造函数
  • 用户声明的复制赋值运算符
  • 用户声明的析构函数
  • 移动赋值运算符不会被隐式定义为已删除 (?)
  • 具有非平凡移动赋值运算符的变体成员,并且是类似联合的类 (?)
  • const 非类类型(或其数组)的非静态数据成员
  • 引用类型的非静态数据成员
  • 具有不可访问的移动赋值运算符且不可简单复制的非静态数据成员
  • 具有不可访问的移动赋值运算符且不可简单复制的直接或虚拟基类

这篇关于编译器何时为类的特殊成员提供定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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