C & C++

C & C++

Made by DeepSource

Possibly unintended type used in shared_ptr CXX-E2001

Bug risk
Major

Finds initializations of C++ shared pointers to non-array type that are initialized with an array.

If a shared pointer std::shared_ptr<T> is initialized with a new-expression new T[], the memory is not deallocated correctly. The pointer uses plain delete in this case to deallocate the target memory. Instead, a delete[] call is needed. A std::shared_ptr<T[]> calls the correct delete operator.

Consider replacing the use of shared_ptr<T> with shared_ptr<T[]> if it is used at a single variable declaration (one variable in one statement).

Bad Practice

std::shared_ptr<Foo> x(new Foo[10]);

std::shared_ptr<Foo> x1(new Foo), x2(new Foo[10]);

std::shared_ptr<Foo> x3(new Foo[10], [](const Foo *ptr) { delete[] ptr; }); // no warning

struct S {
  std::shared_ptr<Foo> x(new Foo[10]);
};

Recommended

std::shared_ptr<Foo[]> x(new Foo[10]);

std::shared_ptr<Foo> x1(new Foo), x2(new Foo[10]);

std::shared_ptr<Foo[]> x3(new Foo[10], [](const Foo *ptr) { delete[] ptr; });

struct S {
  std::shared_ptr<Foo[]> x{new Foo[10]};
};