== Why is this an issue? If you manage memory manually, it's your responsibility to ``++delete++`` all memory created with ``++new++``, and to make sure it's ``++delete++``d once and only once. Ensuring this is done is error-prone, especially when your function can have early exit points. Fortunately, the {cpp} language provides tools that automatically manage memory for you. Using them systematically makes the code simpler and more robust without sacrificing performance. This rule raises an issue when you use: * ``++new++`` - you should prefer a factory function that returns a smart pointer, such as ``++std::make_unique++`` or, if shared ownership is required, ``++std::make_shared++``, * ``++new[]++`` - you should prefer a container class, such as ``++std::vector++``, * ``++delete++`` or ``++delete[]++`` - if you followed the previous advice, there is no need to manually release memory. If your compiler does not support ``++make_unique++``, it's easy to write your own: ---- template std::unique_ptr make_unique(Args&&... args) { return std::unique_ptr(new T(std::forward(args)...)); } ---- === Noncompliant code example [source,cpp] ---- void f() { auto c = new Circle(0, 0, 5); c->draw(); delete c; } ---- === Compliant solution [source,cpp] ---- void f() { auto c = make_unique(0, 0, 5); c->draw(); unique_ptr c2{new Circle(0, 0, 5)}; // Clumsy, but still compliant by exception } ---- === Exceptions If the result of a new is immediately passed as an argument to a function, we assume that the function takes ownership of the newly created object, and won't raise an issue. == Resources * {cpp} Core Guidelines - https://github.com/isocpp/CppCoreGuidelines/blob/e49158a/CppCoreGuidelines.md#r11-avoid-calling-new-and-delete-explicitly[R.11: Avoid calling `new` and `delete` explicitly] * {cpp} Core Guidelines - https://github.com/isocpp/CppCoreGuidelines/blob/e49158a/CppCoreGuidelines.md#c149-use-unique_ptr-or-shared_ptr-to-avoid-forgetting-to-delete-objects-created-using-new[C.149: Use `unique_ptr` or `shared_ptr` to avoid forgetting to `delete` objects created using `new`] ifdef::env-github,rspecator-view[] ''' == Implementation Specification (visible only on this page) === Message Replace the use of "new" with an operation that automatically manages the memory. Rewrite the code so that you no longer need this "delete". ''' == Comments And Links (visible only on this page) === is related to: S5945 === on 9 Nov 2018, 16:33:19 Ann Campbell wrote: Double-check my edits please, [~loic.joly] endif::env-github,rspecator-view[]