Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);

?

like image 313
vladon Avatar asked Jul 12 '16 07:07

vladon


2 Answers

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.

like image 83
Yakk - Adam Nevraumont Avatar answered Oct 15 '22 10:10

Yakk - Adam Nevraumont


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.

like image 31
paweldac Avatar answered Oct 15 '22 11:10

paweldac