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

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


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

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

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


分享到:


相關文章: