>
>
>
V1023. A pointer without owner is added…


V1023. A pointer without owner is added to the container by the 'emplace_back' method. A memory leak will occur in case of an exception.

The analyzer has detected code that adds smart pointers to a container using the 'emplace_back(new X)' method. Such code may cause a memory leak.

Consider the following example:

std::vector<std::unique_ptr<int>> pointers;
pointers.emplace_back(new int(42));

If the vector needs reallocation and fails to allocate a new array, it will throw an exception, and the pointer will be lost.

Fixed code:

pointers.push_back(std::unique_ptr<int>(new int(42)));
pointers.push_back(std::make_unique<int>(42));

Let's examine this type of error in detail.

One cannot simply write 'v.push_back(new X)' to add an element to the end of a container of type 'std::vector<std::unique_ptr<X>>' as there is no implicit cast from 'X*' to 'std::unique_ptr<X>'.

A common solution is to write 'v.emplace_back(new X)' since it compiles successfully: the 'emplace_back' method constructs the element directly from the arguments and, therefore, can use explicit constructors.

However, this is not a safe practice. If the vector is full, the memory is reallocated. Reallocation may fail, causing an 'std::bad_alloc' exception to be thrown. In this case, the pointer will be lost and the object created will never be deleted.

A safer solution is to create a 'unique_ptr', which will own the pointer until the vector attempts to reallocate memory:

v.push_back(std::unique_ptr<X>(new X))

Since C++14, 'std::make_unique' can be used too:

v.push_back(std::make_unique<X>())

This diagnostic is classified as:

You can look at examples of errors detected by the V1023 diagnostic.