c++ - Emplace_back instead of push_back on stl containers? -
i'm not quite sure if can replace push_back emplace_back.
i know emplace_back can forward parameters construct object directly in vector without copying twice (perfect forwarding etc...)
and if soemthing this:
vector<a> o; o.emplace_back(a{}); then should call copy constructor of a. correct ? same push_back. doesn't ?
are there exceptions? there reasons use push_back ? because easier use emplace_back without thinking it.
the main purpose of emplace perform explicit conversions:
#include <chrono> #include <vector> using namespace std::chrono_literals; std::vector<std::chrono::seconds> time; time.push_back(1s); // ok // time.push_back(1); // error, thank god time.emplace_back(1); // ok, assume know you're doing use push_back add element of given value container. use emplace_back explicitly construct element constructor arguments.
Comments
Post a Comment