jeudi 2 mai 2019

How to convert raw to smart pointer when smart pointer is declared in header?

In our code we are mainly using raw pointers and I would like to introduce smart pointers step by step (i.e. without changing existing functions). We have a factory that returns a pointer to a created object. Several methods in the class make use of this object so the pointer to the created object is declared as a class member.

std::unique_ptr<IObject> object;

Now, I would like to replace the raw pointer with a smart pointer.

I found out that I can pass a raw pointer to the constructor of a smart pointer (in my case I think unique_ptr is correct one) but because the smart pointer is declared in the header this does not work. I tried using

object = make_unique<IObject>(CreateObject(1));

but this gives a compilation error because IObject is abstract. The only solution I could find is creating a temporary unique_ptr and then using move.

//Factory.h
std::unique_ptr<IObject> object; 


//Factory.cpp
IObject* ObjectFactory::CreateObject(int type)
{
   switch( type )
   {
      case 1:
         return new A();
      case 2:
        return new B();
   }
}

//My solution is:
 object = std::move( std::unique_ptr<IObject>(ObjectFactory::CreateObject(1)) );

I was wondering if there is a better way than creating a temporary smart pointer and then using move to transfer ownership.

Aucun commentaire:

Enregistrer un commentaire