| 1 |
.. title:: clang-tidy - bugprone-unique-ptr-array-mismatch |
| 2 |
|
| 3 |
bugprone-unique-ptr-array-mismatch |
| 4 |
================================== |
| 5 |
|
| 6 |
Finds initializations of C++ unique pointers to non-array type that are |
| 7 |
initialized with an array. |
| 8 |
|
| 9 |
If a pointer ``std::unique_ptr<T>`` is initialized with a new-expression |
| 10 |
``new T[]`` the memory is not deallocated correctly. A plain ``delete`` is used |
| 11 |
in this case to deallocate the target memory. Instead a ``delete[]`` call is |
| 12 |
needed. A ``std::unique_ptr<T[]>`` uses the correct delete operator. The check |
| 13 |
does not emit warning if an ``unique_ptr`` with user-specified deleter type is |
| 14 |
used. |
| 15 |
|
| 16 |
The check offers replacement of ``unique_ptr<T>`` to ``unique_ptr<T[]>`` if it |
| 17 |
is used at a single variable declaration (one variable in one statement). |
| 18 |
|
| 19 |
Example: |
| 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 array |
| 25 |
std::unique_ptr<Foo> x1(new Foo), x2(new Foo[10]); // no replacement |
| 26 |
// ^ warning: unique pointer to non-array is initialized with array |
| 27 |
|
| 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 case |
| 33 |
// ^ warning: unique pointer to non-array is initialized with array |
| 34 |
}; |
| 35 |
|
| 36 |
This check partially covers the CERT C++ Coding Standard rule |
| 37 |
`MEM51-CPP. Properly deallocate dynamically allocated resources |
| 38 |
<https://wiki.sei.cmu.edu/confluence/display/cplusplus/MEM51-CPP.+Properly+deallocate+dynamically+allocated+resources>`_ |
| 39 |
However, only the ``std::unique_ptr`` case is detected by this check. |