﻿# 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:

```cpp
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:

```cpp
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:

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

Since C\+\+14, 'std::make\_unique' can be used too:

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