We have a similar question in here but I think we haven't got a clear answer the I remake the question.
The C++11 standards has two ways to add a new element in the end of vector they are std::vector::push_back and std::vector::emplace_back.
The difference between them is the std::vector::emplace_back construct the object in place and std::vector::push_back basically copy the object (or primitive type) or move it to the end of vector.
Then std::vector::push_back looks the better option to add primitive types into a std::vector. For example:
std::vector<int> vVec;
vVec.push_back(10);
int iVar 30;
vVec.push_back(iVar);
But it is not so clear to me when we talk about objects. Let's take a vector of std::string for example. If I want to add a literal string I shall use std::vector::emplace_back and when I want to copy or move a string object I shall use std::vector::push_back?
To make more clear what I'm asking about, let's see a few scenarios:
1st scenario:
std::vector<string> vVec;
std::string sTest(“1st scenario”);
vVec.push_back(sTest);
vVec.emplace_back(sTest);
Push_back make a copy of sTest and associate to the new element in the end of vVec meanwhile emplace_back create the string object in the end of vVec and copy the content of sTest into it. Which one is more efficient in this case or doesn't matter?
2nd scenario:
std::vector<string> vVec;
std::string sTest1(“2st scenario”);
std::string sTest2(“2st scenario”);
vVec.push_back(move(sTest1));
vVec.emplace_back(move(sTest2));
Push_back is ready to move semantic, but what happens with emplace_back? Which one is more efficient in this case?
3rd scenario:
std::vector<string> vVec;
std::string sTest("3st scenario");
vVec.push_back(sTest.substr(4,4));
vVec.emplace_back(sTest.substr(4,4));
Because the std::string::substr returns another std::string we have the same situation as the 2nd scenario?
Conclusion
if std::vector::emplace_back is more efficient than std::vector::push_back only when literals is involved (in place construction), does it really justifiable to be used? If does, can you give me some examples?
Important to note that std::vector::emplace_back was implemented in c++11 not in c++0x then I suppose it has a good reason to exists.
Aucun commentaire:
Enregistrer un commentaire