mercredi 4 juillet 2018

Proper way to initilize vector of unique pointer in c++11

For initilizing the vector of unique pointer in c++11, I can consider the following two ways. Which method is better?

#include<memory>
#include<vector>
using namespace std;

int main(){

  const int N = 10000000;

  {//first method
    vector<unique_ptr<int>> vec(N);
    for(auto it=vec.begin(); it!=vec.end();++it){
      auto ptr = make_unique<int>();
      *it = std::move(ptr);
    }
  }

  {//second method
    vector<unique_ptr<int>> vec;
    for(int i=0; i<N; i++){
      vec.push_back(make_unique<int>());
    }
  }
}

Aucun commentaire:

Enregistrer un commentaire