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 |2 Answers
Reset to default 5You 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
values[42];
does the job too. – Marek R Commented Mar 25 at 15:24