40 lines · plain
1.. title:: clang-tidy - bugprone-unique-ptr-array-mismatch2 3bugprone-unique-ptr-array-mismatch4==================================5 6Finds initializations of C++ unique pointers to non-array type that are7initialized with an array.8 9If a pointer ``std::unique_ptr<T>`` is initialized with a new-expression10``new T[]`` the memory is not deallocated correctly. A plain ``delete`` is used11in this case to deallocate the target memory. Instead a ``delete[]`` call is12needed. A ``std::unique_ptr<T[]>`` uses the correct delete operator. The check13does not emit warning if an ``unique_ptr`` with user-specified deleter type is14used.15 16The check offers replacement of ``unique_ptr<T>`` to ``unique_ptr<T[]>`` if it17is used at a single variable declaration (one variable in one statement).18 19Example:20 21.. code-block:: c++22 23 std::unique_ptr<Foo> x(new Foo[10]); // -> std::unique_ptr<Foo[]> x(new Foo[10]);24 // ^ warning: unique pointer to non-array is initialized with array25 std::unique_ptr<Foo> x1(new Foo), x2(new Foo[10]); // no replacement26 // ^ warning: unique pointer to non-array is initialized with array27 28 D d;29 std::unique_ptr<Foo, D> x3(new Foo[10], d); // no warning (custom deleter used)30 31 struct S {32 std::unique_ptr<Foo> x(new Foo[10]); // no replacement in this case33 // ^ warning: unique pointer to non-array is initialized with array34 };35 36This check partially covers the CERT C++ Coding Standard rule37`MEM51-CPP. Properly deallocate dynamically allocated resources38<https://wiki.sei.cmu.edu/confluence/display/cplusplus/MEM51-CPP.+Properly+deallocate+dynamically+allocated+resources>`_39However, only the ``std::unique_ptr`` case is detected by this check.40