C++11新加入了emplace_back()
:
如果要將一個臨時變量push到容器的末尾,push_back()需要先構造臨時對象,再將這個對象拷貝到容器的末尾,而emplace_back()則直接在容器的末尾構造對象,這樣就省去了拷貝的過程。
上代碼:
#include <iostream>
#include <cstring>
#include <vector>
using namespace std;
class A {
public:
A(int i){
str = to_string(i);
cout << "構造函數: " << i << endl;
}
~A(){}
A(const A& other): str(other.str){
cout << "拷貝構造: " << str << endl;
}
public:
string str;
};
int main()
{
vector<A> vec;
vec.reserve(10);
for(int i=0;i<10;i++){
vec.push_back(A(i)); //調用了10次構造函數和10次拷貝構造函數,
// vec.emplace_back(i); //調用了10次構造函數一次拷貝構造函數都沒有調用過
}
}