+ 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
3 Antworten
+ 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