c++11 New emplace_back():

If you want to change a temporary variable push To the end of the container ,push_back() The temporary object needs to be constructed first , Copy the object to the end of the container , and emplace_back() The object is constructed directly at the end of the container , This eliminates the copying process .

Look at the code :
#include <iostream> #include <cstring> #include <vector> using namespace std;
class A { public: A(int i){ str = to_string(i); cout << " Constructor " << endl; }
~A(){} A(const A& other): str(other.str){ cout << " copy construction " << endl; } public:
string str; }; int main() { vector<A> vec; vec.reserve(10); for(int
i=0;i<10;i++){ vec.push_back(A(i)); // Called 10 Secondary constructors and 10 Secondary copy constructor , //
vec.emplace_back(i); // Called 10 The secondary constructor has not been called once by a copy constructor } }
 

Technology