jeudi 4 juin 2015

Lazy initialization of unique_ptr in C++11

I'm developing c++ project in c++11 (gcc 4.8.2). Recently I found unique_ptr is useful for me. Unfortunately I can't use std::make_unique function in my environment. So I tried lazy initialization of unique_ptr by using std::move.

Actually below code works, I don't have confidence in my self. Could you give any comments for better way to initialize unique_ptr? I think my initialization is a little redundancy.

 class AppData {
     public:
         AppData(int id):_id(id){};

         int _id;
         void print() { std::cout << "id is " << _id << std::endl; };
 };

 class Test {
     public:
         Test(){};
         ~Test(){};
         void test();

         std::unique_ptr<AppData> p_data;
 };

 void Test::test() {
     std::unique_ptr<AppData> p(new AppData(3));
     p_data = std::move(p);
     p_data->print();
 }

 int main() {
     Test t;
     t.test();

     return 0;
 }

Aucun commentaire:

Enregistrer un commentaire