c ++语法:默认和删除修饰符 [英] c++ syntax: default and delete modifiers

查看:170
本文介绍了c ++语法:默认和删除修饰符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天,我偶然发现了一个像这样的代码片段:

Today I stumbled over a code snippet like this one:

class A 
{
    A() = default;
    A (const A&) = delete; 

    ...
}

关键字 默认。它们是C ++ 11 std的一部分吗?

I've never seen either the delete or default keyword. Are they part of C++11 std? And what are they used for?

推荐答案

特殊成员函数现在可以默认已删除

Special member functions can now be defaulted or deleted.

删除的成员函数仍然参与重载解析,但如果选择了它,程序就会失败,编译停止,诊断。这是正确的方式写的东西,如非可复制类,并且用户得到一个正确的错误消息。

A deleted member function still takes part in overload resolution, but if it gets chosen, the program is ill-formed and compilation stops with a useful diagnostic. This is The Right Way to write things like non-copyable classes, and the user gets a proper error message.

默认的成员函数做什么应该,例如。默认的默认构造函数默认初始化所有的基数和成员,并有空体;默认复制构造函数复制每个基本和成员对象,并且默认赋值运算符分配每个基本和成员对象。

A defaulted member function "does what it should", e.g. a defaulted default constructor default-initializes all bases and members and has empty body; a defaulted copy constructor copies each base and member object, and a defaulted assignment operator assigns each base and member object. If any of those operations aren't allowed (e.g. you have reference members), then the defaulted member function is defined as deleted.

请注意,您的第一个声明定义

Note that your first declaration-definition A() = default; makes the constructor A::A() user-declared but not user-defined; this is important for the classification of A, e.g. whether it is POD. (And notice that this is different from struct A { A(); }; A::A() = default; which is user-defined.)

另一个好的结果是隐式生成的东西的澄清:如果你不自己编写某些函数(如复制构造函数),则会得到隐式声明。当隐式声明的一个是odr使用时,它被默认定义为,因此如果不可能的话(例如,如果类具有非可复制成员),它实际上被隐式定义已删除。因此,这通常是一个整洁的方式传播的东西,如不可复制性和不可转让性,至少在语言和随之而来的诊断。

Another nice consequence is the clarification of implicitly generated things: If you don't write certain functions yourself at all (like copy constructors), one gets implicitly declared for you. When the implicitly-declared one is odr-used, it gets implicitly defined as defaulted, and thus if it's not possible (e.g. if the class has non-copyable members), it actually gets implicitly defined as deleted. So that's generally a neat way of propagating things like non-copyability and non-assignability, at least in terms of the language and the consequent diagnostics.

这篇关于c ++语法:默认和删除修饰符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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