push_back vs emplace_back | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

push_back vs emplace_back

Hi As per my knowledge, we can use push_back and emplace_back both to add member into vector. First one will create local copy of object and then copies it to vector where as emplace_back directly creates member object into vector space. Is above understanding correct? Why both v.push_back(test()); and v.emplace_back(test()); calls copy and normal constructor both? Should not be a difference in both the calls? https://code.sololearn.com/cA23A11A18a3

17th May 2021, 6:11 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
3 Answers
+ 6
Your understanding is correct. In your code, v.emplace_back(test()) calls default and copy constructor both because you're using it incorrectly. std::vector::emplace_back() only requires the *arguments from which the object is constructed*. So for example, if the constructor of your object takes an int, you will do v.emplace_back(10), not v.emplace_back(obj(10)). See this: https://www.cplusplus.com/reference/vector/vector/emplace_back/ In your code, you are doing v.emplace_back(test()). Here, the test() object is created using the default constructor. Then internally, the emplace_back method uses the argument to construct and object of 'test, something like this test(arg) where arg = test(). This calls the copy constructor. Try changing line 22 to v.emplace_back(); // no arguments, because test::test() requires none And see the difference
17th May 2021, 6:31 AM
XXX
XXX - avatar
+ 1
Thank you XXX nd Infinity
17th May 2021, 7:00 AM
Ketan Lalcheta
Ketan Lalcheta - avatar