Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
459 views
in Technique[技术] by (71.8m points)

c++ - How to emplace object with no-argument constructor into std::map?

I want to emplace an object into a std::map whose constructor does not take any arguments. However, std::map::emplace seems to require at least one additional argument besides the key. So how can I forward zero arguments to the constructor?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The element type of std::map<K, V> is actually std::pair<K, V>, so when you are emplacing into a map, the arguments will be forwarded to the constructor of std::pair. That's why you can't pass just the key: std::pair<K, V> can't be constructed from a single argument (unless it's another pair of the same type.) You can pass zero arguments, but then the key will be value-initialized, which is probably not what you want.

In most cases, moving values will be cheap (and keys will be small and copyable) and you should really just do something like this:

M.emplace(k, V{});

where V is the mapped type. It will be value-initialized and moved into the container. (The move might even be elided; I'm not sure.)

If you can't move, and you really need the V to be constructed in-place, you have to use the piecewise construction constructor...

M.emplace(std::piecewise_construct, std::make_tuple(k), std::make_tuple());

This causes std::pair to construct the first element using k and the second element using zero arguments (value-initialization).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...