C++核心準(zhǔn)則R.11:避免顯示調(diào)用new和delete

R.11: Avoid calling?new?and?delete?explicitly
R.11: 避免顯示調(diào)用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返回的指針應(yīng)該由資源(負(fù)責(zé)調(diào)用delete的)句柄管理。如果new返回的指針賦給原始指針,該對象可能發(fā)生內(nèi)存泄露。
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.
在大規(guī)模程序中,暴露的刪除操作(在應(yīng)用代碼中調(diào)用delete,而不是交給資源管理負(fù)責(zé))有可能引發(fā)bug:如果存在N次delete,你怎么確定你需要的不是N+1或者N-1次?bug可能潛在的:它可能在某次維護(hù)之后發(fā)生。如果存在直接的new操作,可能需要在某處調(diào)用直接的delete操作,因此可能引發(fā)bug。
Enforcement(實(shí)施建議)
(Simple) Warn on any explicit use of?new?and?delete. Suggest using?make_unique?instead.
(簡單)警告任何顯式調(diào)用new和delete的情況。建議使用make_unique。
原文鏈接:
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#r11-avoid-calling-new-and-delete-explicitly
覺得本文有幫助?請分享給更多人。
關(guān)注【面向?qū)ο笏伎肌枯p松學(xué)習(xí)每一天!
面向?qū)ο箝_發(fā),面向?qū)ο笏伎迹?/span>
