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

共 1879字,需浏览 4分钟

 ·

2019-12-30 23:25

5a2d4507b37ec0a08cc84b102c60843e.webp

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

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

8625e068c31aa2061026c604210751e0.webpReason(原因)

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

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

8625e068c31aa2061026c604210751e0.webpExample, problematic(问题示例)
template
// 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 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 v[100] costs 100 allocations.

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

3b054f45acdb689a9f04e63aa4f2dcc7.webp

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

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

8625e068c31aa2061026c604210751e0.webpExample(示例)
template
// 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 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.

  • 提示抛出异常的构造函数。

8625e068c31aa2061026c604210751e0.webp原文链接


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




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

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

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

浏览 21
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报