简体   繁体   中英

simple structs with make_unique and emplace_back

Given a struct:

struct S {
    int x;
    int y;
}

Why the Standard allows us to do this:

std::vector<S> vec;
vec.emplace_back(1, 2);

But does not allow to do this:

auto ptr = std::make_unique<S>(1, 2);

?

Actually neither work.

It was decided that emplace-style construct functions in C++ std would construct with () s not {} s. There is no strong reason why this was chosen (that I know of).

emplace_alt snd make_unique_alt could be added to std where it constructs using {} instead. (a better name should be chosen, naturally)

So the short answer is "because std says so". The medium answer is "it is a near arbitrary choice made by std , followed elsewhere to be consistent". The long answer would involve being in the room where it happened and where it was revisited: this is not a long answer.

Please check your code.

In cpp14 your example code doesn't compile: https://ideone.com/ewyHW6

Both make_unique and emplace_back are using std::forward<Args>(args)... in background, so either both or none compiles.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM