C++核心准则:R.10: 避免使用macloc()和free()

  • 2020 年 3 月 27 日
  • 筆記

R.10: Avoid malloc() and free()

R.10: 避免使用macloc()和free()

Reason(原因)

malloc() and free() do not support construction and destruction, and do not mix well with new and delete.

malloc()和free()不支持构造和析构,和new/delete融合得也不好。

Example(示例)

class Record {      int id;      string name;      // ...  };    void use()  {      // p1 may be nullptr      // *p1 is not initialized; in particular,      // that string isn't a string, but a string-sized bag of bits      Record* p1 = static_cast<Record*>(malloc(sizeof(Record)));        auto p2 = new Record;        // unless an exception is thrown, *p2 is default initialized      auto p3 = new(nothrow) Record;      // p3 may be nullptr; if not, *p3 is default initialized        // ...        delete p1;    // error: cannot delete object allocated by malloc()      free(p2);    // error: cannot free() object allocated by new  }  

In some implementations that delete and that free() might work, or maybe they will cause run-time errors.

在某些实现的的情况下,这里delete和free()可能可以执行,也可能引起执行时错误。

delete释放malloc申请的内存,而free释放的是new构建的对象。

—-译者注

Exception(例外)

There are applications and sections of code where exceptions are not acceptable. Some of the best such examples are in life-critical hard-real-time code. Beware that many bans on exception use are based on superstition (bad) or by concerns for older code bases with unsystematic resource management (unfortunately, but sometimes necessary). In such cases, consider the nothrow versions of new.

有些应用或者代码片段不能接受异常。这方面最好的例子是生命周期敏感的硬实时代码。注意很多关于异常的禁令都是基于(不好的)迷信或者对没有系统进行资源管理的旧代码的担忧(虽然很不幸,但有时是必要的)。这种情况下,考虑不抛出异常的new。

Enforcement(实施建议)

Flag explicit use of malloc and free.

标识出显式使用malloc和free的情况。

原文链接:

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#r10-avoid-malloc-and-free