首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >C++核心准则:R.10: 避免使用malloc()和free()

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

作者头像
面向对象思考
修改2020-03-27 20:50:40
修改2020-03-27 20:50:40
9660
举报

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(示例)

代码语言:javascript
复制
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

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

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • R.10: Avoid malloc() and free()
  • Reason(原因)
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档