2

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 the std::make_unique function in my environment. So I tried lazy initialization of unique_ptr by using std::move.

Actually, the below code works, I don't have confidence in myself. Could you give any comments on better ways to initialize a unique_ptr? I think my initialization is a little redundant.

 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() {
     // I am concerned with this part
     std::unique_ptr<AppData> p(new AppData(3));
     p_data = std::move(p);
     p_data->print();
 }

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

     return 0;
 }
Ryan Haining
  • 35,360
  • 15
  • 114
  • 174
jef
  • 3,890
  • 10
  • 42
  • 76

1 Answers1

6

You could more easily do

p_data.reset(new AppData(3));

rather than going through the extra step of creating a new variable just to move from it. reset will release ownership of the owned object (if any) and free it, then take ownership of the argument.

But make_unique is very easy to implement

To be clear, it would make your Test::test function:

void Test::test() {
    p_data.reset(new AppData(3));
    p_data->print();
}
Community
  • 1
  • 1
Ryan Haining
  • 35,360
  • 15
  • 114
  • 174