Does it ever make practical sense to use emplace_back
with lvalue of some struct S
:
like this:
std::vector<S> v;
auto s = S(/*...*/);
v.emplace_back(s);
Instead of just:
v.emplace_back(/* S constructor arguments */);
or is it just plain misuse of emplace_back
, that only happen to work because const S&
(and thus a copy constructor) is legitimate instantiation for Args... args
inside emplace_back
, and it is not forbidden explicitely?
As you already said, passing const S&
would just invoke the copy constructor.
Unless you intend to use s
in some way before passing it to emplace_back
, it is therefore not necessarily wise.
However, if the code to create s
was, for instance, exceptionally long, it could improve readability to put it and the code for emplace_back
on separate lines. Compilers are extremely good at optimizing such cases and will probably generate the same code anyways (if the copy constructor is default). Basic example: https://godbolt.org/z/D1FClE
If it improves readability or maintainability do it, otherwise there’s no value in it.