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

前端 未结 5 900
后悔当初
后悔当初 2020-12-14 05:40

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

5条回答
  •  盖世英雄少女心
    2020-12-14 06:07

    The element type of std::map is actually std::pair, 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 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).

提交回复
热议问题