Smart pointers and polymorphism

I have applied reference counting pointers (called SP

in the example) and I am having problems with polymorphism, which I think it shouldn't be.

In the following code:

    SP<BaseClass> foo()
    {   
        // Some logic...
        SP<DerivedClass> retPtr = new DerivedClass();
        return retPtr;
    }

      

DerivedClass

inherited from BaseClass

. With normal pointers, this should have worked, but with smart pointers, it speaks "cannot convert from 'SP<T>' to 'const SP<T>&"

and I think it refers to the smart pointer copy constructor.

How to resolve this kind of polymorphism with reference counting pointer? I would appreciate some code examples because obviously I am doing something wrong here if I am having this problem.

PS: Please don't tell me to use the standard library with smart pointers because that is not possible at the moment.

+2


a source to share


4 answers


Pretty obvious:

SP<DerivedClass> retPtr = new DerivedClass();

      



it should be:

SP<BaseClass> retPtr = new DerivedClass();

      

+6


a source


You must add an implicit conversion constructor for SP<T>

:



template<class T>
struct SP {
   /// ......
   template<class Y>
   SP( SP <Y> const & r )
    : px( r.px ) // ...
    {
    }

   //....
private:
   T * px;
}

      

+4


a source


Why not add a template assignment operator:

template <class Base>
class SP
{
    ...

    template<class Derived>
    operator = (SP<Derived>& rhs)
    {
        ...

      

(and possibly a copy constructor as well)?

0


a source


In addition to the copy constructor:

SP(const SP<T>& ref);

      

you need a conversion constructor:

template<typename T2>
SP(const SP<T2>& ref);

      

Otherwise, the compiler doesn't know how to build SP<BaseClass>

from SP<DerivedClass>

; for him they are not related.

The conversion constructor is pretty trivial, as inside you can automatically convert *DerivedClass

to *BaseClass

. The code can be very similar to the code for the copy constructor.

0


a source







All Articles