c++ - How to use std::map::emplace to add a default constructed value when it is not movable - Stack Overflow

This compiles:#include <map>struct S {int val = 0;S() = default;S(S&&) = default;};int

This compiles:

#include <map>

struct S {
    int val = 0;
    S() = default;
    S(S&&) = default;
};
int main() {
    std::map<int, S> values;
    values.emplace(42, S{});
}

LIVE

This does not:

#include <map>

struct S {
    int val = 0;
    S() = default;
    S(S&&) = delete;
};
class Wrapper {
   public:
    std::map<int, S> values;
    void AddEmptyValue(int key, int) { values.emplace(key, S{}); }
};

LIVE
(it's not surprising as we're building a S rvalue what would have to be moved to the second part of a std::pair but S is not movable).

How can I just pass a key and let the value be default-constructed?

This compiles:

#include <map>

struct S {
    int val = 0;
    S() = default;
    S(S&&) = default;
};
int main() {
    std::map<int, S> values;
    values.emplace(42, S{});
}

LIVE

This does not:

#include <map>

struct S {
    int val = 0;
    S() = default;
    S(S&&) = delete;
};
class Wrapper {
   public:
    std::map<int, S> values;
    void AddEmptyValue(int key, int) { values.emplace(key, S{}); }
};

LIVE
(it's not surprising as we're building a S rvalue what would have to be moved to the second part of a std::pair but S is not movable).

How can I just pass a key and let the value be default-constructed?

Share Improve this question edited Mar 25 at 15:25 NathanOliver 181k29 gold badges316 silver badges430 bronze badges asked Mar 25 at 14:59 OerstedOersted 2,9486 silver badges29 bronze badges 1
  • values[42]; does the job too. – Marek R Commented Mar 25 at 15:24
Add a comment  | 

2 Answers 2

Reset to default 5

You need to use the std::piecewise_construct tag like

values.emplace(std::piecewise_construct,
               std::forward_as_tuple(42),
               std::forward_as_tuple());

in order to tell emplace that the key should be constructed with 42 and the value should be constructed with nothing, which will use the default constructor.

Use try_emplace instead.

values.try_emplace(key);

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744187511a4562276.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信