前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则C.44:默认构造函数最好简单而且不会抛出异常

C++核心准则C.44:默认构造函数最好简单而且不会抛出异常

作者头像
面向对象思考
发布2020-03-25 16:10:48
3910
发布2020-03-25 16:10:48
举报
文章被收录于专栏:C++核心准则原文翻译

C.44: Prefer default constructors to be simple and non-throwing

C.44:默认构造函数最好简单而且不会抛出异常

Reason(原因)

Being able to set a value to "the default" without operations that might fail simplifies error handling and reasoning about move operations.

默认构造函数可以将内容设置到默认状态而不需要可能引起失败的操作,简化了错误处理和针对移动操作的推测。

Example, problematic(问题示例)

代码语言:javascript
复制
template<typename T>
// elem points to space-elem element allocated using new
class Vector0 {
public:
    Vector0() :Vector0{0} {}
    Vector0(int n) :elem{new T[n]}, space{elem + n}, last{elem} {}
    // ...
private:
    own<T*> elem;
    T* space;
    T* last;
};

This is nice and general, but setting a Vector0 to empty after an error involves an allocation, which may fail. Also, having a default Vector represented as {new T[0], 0, 0} seems wasteful. For example, Vector0<int> v[100] costs 100 allocations.

这段代码整洁且普通,但是如果过在涉及到内存分配的错误之后生成一个空的Vector0对象时,可能会失败。同时,让默认的Vector表现为{new T[0], 0, 0}有些浪费。例如Vector0<int>v[100]需要100次内存分配。

100次内存分配似乎有些问题。译者的理解是只要一次分配100个整数的空间就好。

另外new T[0]有点奇怪。

Example(示例)

代码语言:javascript
复制
template<typename T>
// elem is nullptr or elem points to space-elem element allocated using new
class Vector1 {
public:
    // sets the representation to {nullptr, nullptr, nullptr}; doesn't throw
    Vector1() noexcept {}
    Vector1(int n) :elem{new T[n]}, space{elem + n}, last{elem} {}
    // ...
private:
    own<T*> elem = nullptr;
    T* space = nullptr;
    T* last = nullptr;
};

Using {nullptr, nullptr, nullptr} makes Vector1{} cheap, but a special case and implies run-time checks. Setting a Vector1 to empty after detecting an error is trivial.

使用{nullptr, nullptr, nullptr}让Vector1{}的代价更小,但是特殊的情况,(由于产生了没有数据的情况,译者注)需要运行时检查。在检测到错误之后将Vector1设为空的处理是小事情。

Enforcement(实施建议)
  • Flag throwing default constructors.
  • 提示抛出异常的构造函数。

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c44-prefer-default-constructors-to-be-simple-and-non-throwing


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

关注【面向对象思考】轻松学习每一天!

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

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2019-12-30,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Enforcement(实施建议)
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档