C.43: Ensure that a copyable (value type) class has a default constructor

C.43:确保(值类型)可拷贝类有默认构造函数

Reason(原因)

Many language and library facilities rely on default constructors to initialize their elements, e.g. T a[10] and std::vector v(10). A default constructor often simplifies the task of defining a suitable moved-from state for a type that is also copyable.

很多语言和库设施依靠默认构造函数来初始化它们的元素,例如T a[0]和std::vectorv(10)。默认构造函数经常可以简化为可拷贝类定义适当的移出状态的工作。

Note(注意)

A value type is a class that is copyable (and usually also comparable). It is closely related to the notion of Regular type from EoP and the Palo Alto TR.

可拷贝(通常也是可比较)的类称为值类型。它和《编程原本》和《STL概念设计》中提到的正规类型之间的联系非常紧密。

正规类型:https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#SS-concrete

编程原本:http://elementsofprogramming.com/

STL概念设计:http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3351.pdf

Example(示例)

class Date { // BAD: no default constructorpublic:    Date(int dd, int mm, int yyyy);    // ...};vector vd1(1000);   // default Date needed herevector vd2(1000, Date{Month::October, 7, 1885});   // alternative

The default constructor is only auto-generated if there is no user-declared constructor, hence it's impossible to initialize the vectorvd1in the example above. The absence of a default value can cause surprises for users and complicate its use, so if one can be reasonably defined, it should be.、

默认构造函数只有在不存在用户定义构造函数时才会自动生成,因此像上面代码中vector vd1那样的初始化是不可能的。默认值的缺失可能令用户感到意外并且增大使用的难度,因此如果有可能合理地定义它,就那样做。

Date is chosen to encourage thought: There is no "natural" default date (the big bang is too far back in time to be useful for most people), so this example is non-trivial.{0, 0, 0} is not a valid date in most calendar systems, so choosing that would be introducing something like floating-point's NaN. However, most realistic Date classes have a "first date" (e.g. January 1, 1970 is popular), so making that the default is usually trivial.

选择日期类是为了推进思考:不存在"自然"的默认日期(对于大多数人来说,以宇宙大爆炸的时刻作为默认值需要将时间回退的太多了,不具备实际意义),因此这个例子不具备一般性。{0,0,0}在大多数日历系统中都不是合法的日期,因此选择它将会引起类似浮点数的NaN问题。

NaN:不是数字,或者说无效数字。

class Date {public:    Date(int dd, int mm, int yyyy);    Date() = default; // [See also](#Rc-default)    // ...private:    int dd = 1;    int mm = 1;    int yyyy = 1970;    // ...};vector vd1(1000);

Note(注意)

A class with members that all have default constructors implicitly gets a default constructor:

如果一个类的所有成员都有默认构造函数,那么这个类也隐式得到一个默认构造函数。

struct X {    string s;    vector v;};X x; // means X{{}, {}}; that is the empty string and the empty vector

Beware that built-in types are not properly default constructed:

注意:内置类型没有被正确地默认构造:

struct X {    string s;    int i;};void f(){    X x;    // x.s is initialized to the empty string; x.i is uninitialized    cout << x.s << ' ' << x.i << '';    ++x.i;}

Statically allocated objects of built-in types are by default initialized to 0, but local built-in variables are not. Beware that your compiler may default initialize local built-in variables, whereas an optimized build will not. Thus, code like the example above may appear to work, but it relies on undefined behavior. Assuming that you want initialization, an explicit default initialization can help:

静态分配的内置类型被默认初始化为0,办事局部的内置类型没有。注意你的编译器有可能初始化局部的内置类型变量,尽管优化状态的编译不会。因此上面示例中的代码看起来可以动作,但是者依靠(编译器,译者注)没有定义的行为。如果你需要初始化,明确的默认初始化可以帮忙:

struct X {    string s;    int i {};   // default initialize (to 0)};

Notes(注意)

Classes that don't have a reasonable default construction are usually not copyable either, so they don't fall under this guideline.

不包含合理的默认构造动作的类通常也不是可拷贝的,因此它们不算对本准则的违反。

For example, a base class is not a value type (base classes should not be copyable) and so does not necessarily need a default constructor:

例如,基类不是值类型(基类不应该可拷贝)而且不需要默认构造函数。

// Shape is an abstract base class, not a copyable value type.// It may or may not need a default constructor.struct Shape {    virtual void draw() = 0;    virtual void rotate(int) = 0;    // =delete copy/move functions    // ...};

A class that must acquire a caller-provided resource during construction often cannot have a default constructor, but it does not fall under this guideline because such a class is usually not copyable anyway:

一个类如果必须在构造期间要求调用者提供资源,通常不能拥有默认构造函数,但是它没有违反本准则,因为这样的类通常无论如何也是不能拷贝的。

// std::lock_guard is not a copyable value type.// It does not have a default constructor.lock_guard g {mx};  // guard the mutex mxlock_guard g2;      // error: guarding nothing

A class that has a "special state" that must be handled separately from other states by member functions or users causes extra work (and most likely more errors). Such a type can naturally use the special state as a default constructed value, whether or not it is copyable:

有的类具有某种“特殊状态”,必须通过成员函数或者用户引发(最有可能是错更多的错误)的特别动作彼此分开进行处理。这样的类型可以自然地使用特殊状态作为默认构造的初始值,不管它是否是可拷贝的。

// std::ofstream is not a copyable value type.// It does happen to have a default constructor// that goes along with a special "not open" state.ofstream out {"Foobar"};// ...out << log(time, transaction);

Similar special-state types that are copyable, such as copyable smart pointers that have the special state "==nullptr", should use the special state as their default constructed value.

类似的可拷贝的特殊状态类型,例如包含“==nullprt"这样的特殊状态的可拷贝的智能指针,应该使用特殊状态作为它们默认构造的初始值。

However, it is preferable to have a default constructor default to a meaningful state such as std::strings "" and std::vectors {}.

然而,更可取的做法是让默认构造函数默认生成一个有意义的状态,例如std::string的“”和std::vectors{}。

Enforcement(实施建议)

  • Flag classes that are copyable by = without a default constructor如果类实现了赋值运算符但却没有构造函数,进行提示。
  • Flag classes that are comparable with == but not copyable如果类可以通过比较运算符进行比较但却不是可拷贝的,进行提示。

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c43-ensure-that-a-copyable-value-type-class-has-a-default-constructor


觉得本文有帮助?请分享给更多人。

更多文章请关注微信公众号【面向对象思考】!

面向对象开发,面向对象思考!

move std 函数 示例_确保(值类型)可拷贝类有默认构造函数相关推荐

  1. C++核心准则C.43:保证(值类型)可拷贝类有默认构造函数

    C.43: Ensure that a copyable (value type) class has a default constructor C.43:确保(值类型)可拷贝类有默认构造函数 Re ...

  2. move std 函数 示例_C++11右值引用和std::move语句实例解析(推荐)

    右值引用(及其支持的Move语意和完美转发)是C++0x将要加入的最重大语言特性之一.从实践角度讲,它能够完美解决C++中长久以来为人所诟病的临时对象效率问题.从语言本身讲,它健全了C++中的引用类型 ...

  3. move std 函数 示例_C++ STL迭代器辅助函数

    advance(it, n) ---------- it 表示某个迭代器,n 为整数.该函数的功能是将 it 迭代器前进或后退 n 个位置.distance(first, last) -------- ...

  4. Python函数常见return返回值类型

    Python函数常见return返回值类型Python函数return返回值类型主要包括: class 'int', class 'str', class 'tuple', class 'list', ...

  5. python函数示例_带Python示例的complex()函数

    python函数示例 Python complex()函数 (Python complex() function) complex() function is a library function i ...

  6. python函数示例_使用Python中的示例的input()函数

    python函数示例 Python input()函数 (Python input() function) input() function is a library function, it is ...

  7. python返回变量类型_Python指定函数参数、返回值类型报错是咋了?

    Leetcode刷题给的默认函数格式是这样的: Class Solution: def coinChange(self, coins: List[int], amount: int) -> in ...

  8. python函数示例_带Python示例的float()函数

    python函数示例 Python float()函数 (Python float() function) float() function is a library function in Pyth ...

  9. python 匿名函数示例_扣丁学堂Python3开发之匿名函数用法示例详解

    扣丁学堂Python3开发之匿名函数用法示例详解 2018-07-26 14:01:11 1324浏览 今天扣丁学堂Python培训给大家分享关于Python3匿名函数用法,结合实例形式分析了Pyth ...

最新文章

  1. 微软笔试题 2013暑期实习笔试题目
  2. 通过简单的Word Count讲解MapReduce原理以及Java实现
  3. linux 显示文件多少行
  4. CS229-Lesson7最优间隔分类器
  5. nyoj 628 小媛在努力= =(水)
  6. FL studio 20简易入门教程 -- 第六篇 -- 调音台和自动化包络线
  7. masm汇编语言linux命令,Windows10下利用DOSBOX和MASM32搭建汇编语言开发环境
  8. Jsp中getParameter、getParameterValues、getParameterNames和getParameterMap用法详解
  9. Python 实现的、带GUI界面的词云生成器
  10. ico图标生成器系统 断网情况下快速生成ico文件
  11. 计算机是1946年由科学家发明,1946年第一台计算机叫什么
  12. 计算机网络安全及故障谢辞,计算机网络安全初探.pdf
  13. matlab连接mysql有什么用_MATLAB连接SQLServer和MySql数据库
  14. 黑马程序员Netty全套教程,全网最全Netty深入浅出教程,Java网络编程的王者
  15. 滴滴裁员2000人启示:牛逼的人,都有铁饭碗
  16. XAMP下tomcat无法启动:Make sure you have Java JDK or JRE installed and the required ports are free解决方法
  17. Qt音视频开发06-海康sdk内核linux客户端
  18. QrCode类生成二维码海报
  19. 一文读懂通信玩家半年财报,有人欢喜有人愁!
  20. python中的解码与编码

热门文章

  1. python编程培训多少钱-线下python培训要多少钱?
  2. python经典案例-Python递归的经典案例
  3. python装饰器-装饰器
  4. python语言能做什么软件-什么是Python语言,Python语言可以用来做什么?
  5. python的编程模式-Python设计模式:为了整洁又时尚的代码
  6. 流程的python-流畅的Python
  7. 简单比较python语言和c语言的异同-Python快速入门之与C语言异同
  8. python管理系统-员工管理系统源程序(python实现)
  9. python100行代码-python代码行数统计 100行
  10. python真的这么厉害吗-Python为什么这么厉害?——Python ,能用来做什么