37 lines · plain
1.. title:: clang-tidy - bugprone-shared-ptr-array-mismatch2 3bugprone-shared-ptr-array-mismatch4==================================5 6Finds initializations of C++ shared pointers to non-array type that are7initialized with an array.8 9If a shared pointer ``std::shared_ptr<T>`` is initialized with a new-expression10``new T[]`` the memory is not deallocated correctly. The pointer uses plain11``delete`` in this case to deallocate the target memory. Instead a ``delete[]``12call is needed. A ``std::shared_ptr<T[]>`` calls the correct delete operator.13 14The check offers replacement of ``shared_ptr<T>`` to ``shared_ptr<T[]>`` if it15is used at a single variable declaration (one variable in one statement).16 17Example:18 19.. code-block:: c++20 21 std::shared_ptr<Foo> x(new Foo[10]); // -> std::shared_ptr<Foo[]> x(new Foo[10]);22 // ^ warning: shared pointer to non-array is initialized with array [bugprone-shared-ptr-array-mismatch]23 std::shared_ptr<Foo> x1(new Foo), x2(new Foo[10]); // no replacement24 // ^ warning: shared pointer to non-array is initialized with array [bugprone-shared-ptr-array-mismatch]25 26 std::shared_ptr<Foo> x3(new Foo[10], [](const Foo *ptr) { delete[] ptr; }); // no warning27 28 struct S {29 std::shared_ptr<Foo> x(new Foo[10]); // no replacement in this case30 // ^ warning: shared pointer to non-array is initialized with array [bugprone-shared-ptr-array-mismatch]31 };32 33This check partially covers the CERT C++ Coding Standard rule34`MEM51-CPP. Properly deallocate dynamically allocated resources35<https://wiki.sei.cmu.edu/confluence/display/cplusplus/MEM51-CPP.+Properly+deallocate+dynamically+allocated+resources>`_36However, only the ``std::shared_ptr`` case is detected by this check.37