Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize a unique_ptr

I'm trying to add a lazy-initialization function to my class. I'm not very proficient with C++. Can someone please tell me how I achieve it.

My class has a private member defined as:

std::unique_ptr<Animal> animal; 

Here's the original constructor that takes one parameter:

MyClass::MyClass(string file) : animal(new Animal(file)) {} 

I just added a parameter-less constructor and an Init() function. Here's the Init function I just added:

void MyClass::Init(string file) {     this->animal = ???; } 

What do I need to write there to make it equivalent to what constructor is doing?

like image 925
dotNET Avatar asked Sep 17 '15 06:09

dotNET


People also ask

How do you initialize a unique pointer to null?

You don't need to initialize the std::unique pointer to null. Just leave it as its default empty value in the constructor and only ever reset it to point to a non-null pointer.

What does unique_ptr Reset do?

std::unique_ptr::resetDestroys the object currently managed by the unique_ptr (if any) and takes ownership of p. If p is a null pointer (such as a default-initialized pointer), the unique_ptr becomes empty, managing no object after the call.


1 Answers

#include <memory> #include <algorithm> #include <iostream> #include <cstdio>  class A { public :     int a;     A(int a)     {         this->a=a;      } }; class B { public :     std::unique_ptr<A> animal;     void Init(int a)     {         this->animal=std::unique_ptr<A>(new A(a));     }     void show()     {         std::cout<<animal->a;     } };  int main() {     B *b=new B();     b->Init(10);     b->show();     return 0; } 
like image 181
Menos Avatar answered Sep 20 '22 09:09

Menos