I'm using C++ 11 and gcc-4.7.0. I'm looking for an STL solution.
I'd like to have an unsorted multimap that contains objects of myClass with short strings as keys. Emplace looks like a good way to put the objects into the map as I construct them, but I'm not sure if it can do that, or if it will only construct the key/object pair. This should be valid:
table.emplace(myKey, myClass(arg1, arg2, arg3));
But would it be more efficient to do the following, and is it even valid code?
table.emplace(myKey, arg1, arg2, arg3);
According to this, gcc-4.7
does not fully support emplace()
.
gcc-4.8
would have fully support of emplace()
, but would require a little differnt syntax:
table.emplace(std::piecewise_construct, std::forward_as_tuple(myKey), std::forward_as_tuple(arg1, arg2, arg3));
instead of
table.emplace(myKey, arg1, arg2, arg3); // Does not work.
For forward
to take effect for rvalue, one could use std::move()
to wrap around the arguments.
So it will directly contruct both key and value in place in the container.
std::piecewise_construct
is an argument for special usage of std::pair
constructor. It will ask the constructor to forward the arguments individually to underlying constructor.
This is actually an issue of emplace()
for associative containers. The original intention is to use the first argument for key, and the following arguments for value, like what is described in the question. See this for further details on this issue.
Thanks to Zeta, for pointing out forward
issue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With