samedi 28 novembre 2015

The correct way of returning std::unique_ptr to an object of polymorphic class

Let's say I have the following hierarchy of classes:

struct Base 
{
};

struct Derived : public Base 
{ 
    void DoStuffSpecificToDerivedClass() 
    {
    } 
};

And the following factory method:

std::unique_ptr<Base> factoryMethod()
{
    auto derived = std::make_unique<Derived>();
    derived->DoStuffSpecificToDerivedClass();
    return derived;
}

The problem is, the return statement does not compile, because std::unique_ptr does not have a copy constructor with covariance support (which makes sense since it does not have any copy constructors), it only has a move constructor with covariance support.

What is the best way to make solve this problem? I can think of two ways:

return std::move(derived); // 1
return std::unique_ptr<Base>(derived.release()); // 2

P.S. I'm using Visual C++ 2013 as my compiler. The original error message looks like this:

Error   1   error C2664: 'std::unique_ptr<Base,std::default_delete<_Ty>>::unique_ptr(const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)' : cannot convert argument 1 from 'std::unique_ptr<Derived,std::default_delete<Derived>>' to 'std::unique_ptr<Derived,std::default_delete<Derived>> &&'

Aucun commentaire:

Enregistrer un commentaire