I\'m a bit confused regarding the difference between push_back
and emplace_back
.
void emplace_back(Type&& _Val);
void push_
Optimization for emplace_back
can be demonstrated in next example.
For emplace_back
constructor A (int x_arg)
will be called. And for
push_back
A (int x_arg)
is called first and move A (A &&rhs)
is called afterwards.
Of course, the constructor has to be marked as explicit
, but for current example is good to remove explicitness.
#include
#include
class A
{
public:
A (int x_arg) : x (x_arg) { std::cout << "A (x_arg)\n"; }
A () { x = 0; std::cout << "A ()\n"; }
A (const A &rhs) noexcept { x = rhs.x; std::cout << "A (A &)\n"; }
A (A &&rhs) noexcept { x = rhs.x; std::cout << "A (A &&)\n"; }
private:
int x;
};
int main ()
{
{
std::vector a;
std::cout << "call emplace_back:\n";
a.emplace_back (0);
}
{
std::vector a;
std::cout << "call push_back:\n";
a.push_back (1);
}
return 0;
}
output:
call emplace_back:
A (x_arg)
call push_back:
A (x_arg)
A (A &&)