Many STL containers (vector,map etc) support both insert and emplace operations,
vector => push_back vs emplace_back
map => insert vs emplace
Emplace semantics support in-place construction, which is why they're fast.
Okay, we've introduced yet another jargon here, In-Place construction, what is it and why is it better.To understand this, We need to take a look at what push_back does to a vector
push_back
a. Create an object in stack
b. Copy the object from stack to vector memory
As you might be aware, copying is one of the primal sins when it comes to performance. We need to eliminate it as much as we can. This is where emplace_back fits right in.
emplace_back
a. Creates object directly inside vector's memory thus avoiding the need for a copy operation
Following code snippet, shows the nitty gritties of both operations,
#include<string>
#include<vector>
#include<iostream>
struct Chocolate
{
std::string name;
std::string origin;
Chocolate(std::string p_name, std::string p_origin )
: name(std::move(p_name)),
origin(std::move(p_origin))
{
std::cout << " Chocolate Construct operation\n";
}
Chocolate(Chocolate&& other)
: name(std::move(other.name)),
origin(std::move(other.origin))
{
std::cout << "Chocolate Move operation\n";
}
Chocolate& operator=(const Chocolate& other) = default;
};
int main()
{
std::vector<Chocolate> giftbox1;
giftbox1.emplace_back("Dark Chocolate", "Ghana");
std::vector<Chocolate> giftbox2;
giftbox2.push_back(Chocolate("Milk Chocolate", "Tanzania"));
// Unbox the content of both giftboxes
for (const Chocolate& choco: giftbox1)
std::cout << choco.name << " is from "<<choco.origin<<"\n";
for (const Chocolate& choco: giftbox2)
std::cout << choco.name << " is from "<<choco.origin<<"\n";
}
Run this example in gcc, observe the output to infer the difference between push_back and emplace_back
That all for today, Have a great one ☕