jeudi 28 avril 2016

Why does std::vector::emplace call destructor without any copy constructor called?

I am storing objects inside a std::vector, and I want to avoid calling destructor as much as possible.
I replaced copy constructor and assignments by move ones:

class Object
{
    Object(const Object&) = delete;
    Object(Object&&);
    Object& operator=(const Object&) = delete;
    Object& operator=(Object&&);
    [...]
};

I am initializing it like this:

std::vector<Object>   container;

container.reserve(42) // Reserve a lot in order to be sure it won't be a problem

Then, I add two elements with emplace_back (the constructor takes one int parameter):

container.emplace_back(1);
container.emplace_back(3);

Until there, everything is fine. But then I want to insert an element before the last one with emplace:

auto it = container.end();

it--; // Last position.
it--; // Before last position.
container.emplace(it, 2);

But here a destructor is called.

I tried to locate why with Valgrind, it appears emplace function calls _M_insert_aux that call my destructor.

How could I avoid that?

Aucun commentaire:

Enregistrer un commentaire