๐๐ฎ๐๐๐น๐ฒ ๐ผ๐ณ ๐ฆ๐ง๐: ๐ฝ๐๐๐ต_๐ฏ๐ฎ๐ฐ๐ธ ๐๐ ๐ฒ๐บ๐ฝ๐น๐ฎ๐ฐ๐ฒ_๐ฏ๐ฎ๐ฐ๐ธ โ ๐ช๐ต๐ผโ๐ ๐๐ฎ๐๐๐ฒ๐ฟ?
C++ STL is full of little optimisations that can make a huge difference in performance when dealing with large datasets. One such pair of functions that often causes confusion is push_back vs emplace_back.
Letโs break it down in simple terms.
The Basics
push_backโ Adds an element to the end of a container by copying or moving it.emplace_backโ Constructs the element directly at the end of the container (in-place construction).
Example:
#include <bits/stdc++.h>
using namespace std;struct Student {
string name;
int age;
Student(string n, int a) : name(n), age(a) {
cout << "Constructor called for " << name << endl;
}
Student(const Student& s) {
cout << "Copy constructor called for " << s.name << endl;
}
};int main() {
vector<Student> students;
cout << "--- Using push_back ---" << endl;
students.push_back(Student("Gita", 21));
cout << "--- Using emplace_back ---" << endl;
students.emplace_back("Sita", 20);
}
Output:
--- Using push_back ---
Constructor called for Gita
Copy constructor called for Gita--- Using emplace_back ---
Constructor called for SitaNotice the difference:
- With
push_back, the object is constructed outside and then copied/moved inside the vector. - With
emplace_back, it is constructed directly inside the vector โ avoiding the extra copy.
When to Use What?
- Use
emplace_backwhen you are creating an object directly in the container. - Use
push_backwhen you already have an object created.
Example:
Student s("Ram", 22);
students.push_back(s); // Correct
students.emplace_back(s); // Not efficient herePerformance Impact
For lightweight objects like integers or chars โ negligible difference.
For complex objects (like classes with expensive constructors, strings, pairs, or nested containers) โ emplace_back gives a significant performance boost.
Takeaway
emplace_back is not just syntactic sugar. It allows direct in-place construction, reducing unnecessary copies or moves, making your code both faster and cleaner.
Get Vidhi koulโs stories inย yourย inbox
Join Medium for free to get updates fromย thisย writer.
๐ Rule of thumb:
- If constructing on the fly โ use
emplace_back. - If you already have the object โ use
push_back.
โก Small change, big impact. Thatโs the beauty of C++!







