vigs1990
vigs1990

Reputation: 1699

C++ move guarantees during map insertion

I have a code snippet which looks somewhat like this:

std::unordered_map<FooId, Foo> fooMap;
Foo foo1(..);
fooMap.emplace(foo1.id(), std::move(foo1));

Is the emplace safe, i.e. does the C++ language standard guarantee that foo1.id() is invoked before std::move(foo1)?

Upvotes: 3

Views: 196

Answers (1)

Mike Seymour
Mike Seymour

Reputation: 254461

You're asking the wrong question: std::move does nothing, so it doesn't matter that the function arguments aren't evaluated in a specified order.

What matters is that foo1.id() is invoked before the call to emplace, which moves from the reference to foo1 provided by std::move. That is the case - function calls are always sequenced after the evaluation of their arguments.

This code is safe as long as id() returns a value, not a reference to something that might be destroyed or invalidated by the move.

Upvotes: 7

Related Questions