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

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

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

<code>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
}/<record>/<code>

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


覺得本文有幫助?請分享給更多人。

關注【面向對象思考】輕鬆學習每一天!

面向對象開發,面向對象思考!


分享到:


相關文章: