jeudi 5 mai 2016

At which point does map::emplace create an object?

Is the point at which std::map::emplace creates the object (i.e. call the constructor) specified somehow in standard? If yes, does it happen before existence of such key is checked or after?

It matters a lot in the cases like following:

struct X {};
std::map<int, std::unique_ptr<X> > map;

void f(int x) {
    map.emplace(x, new X);
}

If object is created first, all is cool (unique_ptr is constructed and owns the resource), but if it is constructed after the check, there is a memory leak in case of a duplicate key.

All I was able to find in Standard is

Inserts a value_type object t constructed with std::forward<Args>(args)... if and only if there is no element in the container with key equivalent to the key of t.

which doesn't address the question I have.

Aucun commentaire:

Enregistrer un commentaire