1. 程式人生 > 實用技巧 >c++11 push_back與emplace_back之間的區別

c++11 push_back與emplace_back之間的區別

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 << "建構函式" << endl; 
    }
    ~A(){}
    A(const A& other): str(other.str){
        cout << "拷貝構造" << 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次建構函式一次拷貝建構函式都沒有呼叫過
    }
 
}

  

https://blog.csdn.net/shaochuang1/article/details/100171597