xref: /llvm-project/clang-tools-extra/docs/clang-tidy/checks/bugprone/unique-ptr-array-mismatch.rst (revision b0bab14b8b5305ddcb4e8b4d8a0e64004fc5425e)
1.. title:: clang-tidy - bugprone-unique-ptr-array-mismatch
2
3bugprone-unique-ptr-array-mismatch
4==================================
5
6Finds initializations of C++ unique pointers to non-array type that are
7initialized with an array.
8
9If 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
11in this case to deallocate the target memory. Instead a ``delete[]`` call is
12needed. A ``std::unique_ptr<T[]>`` uses the correct delete operator. The check
13does not emit warning if an ``unique_ptr`` with user-specified deleter type is
14used.
15
16The check offers replacement of ``unique_ptr<T>`` to ``unique_ptr<T[]>`` if it
17is 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 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
36This 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>`_
39However, only the ``std::unique_ptr`` case is detected by this check.
40