千家信息网

C++中避免使用macloc()和free()的原因是什么

发表于:2025-02-05 作者:千家信息网编辑
千家信息网最后更新 2025年02月05日,本篇文章给大家分享的是有关C++中避免使用macloc()和free()的原因是什么,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。Rea
千家信息网最后更新 2025年02月05日C++中避免使用macloc()和free()的原因是什么

本篇文章给大家分享的是有关C++中避免使用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(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()可能可以执行,也可能引起执行时错误。

以上就是C++中避免使用macloc()和free()的原因是什么,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注行业资讯频道。

0