天天看點

C++核心準則R.11:避免顯示調用new和delete

R.11: Avoid calling new and delete explicitly

R.11: 避免顯示調用new和delete

Reason(原因)

The pointer returned by new should belong to a resource handle (that can call delete). If the pointer returned by new is assigned to a plain/naked pointer, the object can be leaked.

new傳回的指針應該由資源(負責調用delete的)句柄管理。如果new傳回的指針賦給原始指針,該對象可能發生記憶體洩露。

Note(注意)

In a large program, a naked delete (that is a delete in application code, rather than part of code devoted to resource management) is a likely bug: if you have N deletes, how can you be certain that you don't need N+1 or N-1? The bug may be latent: it may emerge only during maintenance. If you have a naked new, you probably need a naked delete somewhere, so you probably have a bug.

在大規模程式中,暴露的删除操作(在應用代碼中調用delete,而不是交給資源管理負責)有可能引發bug:如果存在N次delete,你怎麼确定你需要的不是N+1或者N-1次?bug可能潛在的:它可能在某次維護之後發生。如果存在直接的new操作,可能需要在某處調用直接的delete操作,是以可能引發bug。

Enforcement(實施建議)

(Simple) Warn on any explicit use of new and delete. Suggest using make_unique instead.

(簡單)警告任何顯式調用new和delete的情況。建議使用make_unique。

原文連結:

​​https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#r11-avoid-calling-new-and-delete-explicitly​​

繼續閱讀