天天看点

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​​

继续阅读