简体   繁体   中英

Smart pointers and polymorphism

I implemented reference counting pointers (called SP in the example) and I'm having problems with polymorphism which I think I shouldn't have.

In the following code:

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

DerivedClass inherits from BaseClass . With normal pointers this should have worked, but with the smart pointers it says "cannot convert from 'SP<T>' to 'const SP<T>&" and I think it refers to the copy constructor of the smart pointer.

How do I allow this kind of polymorphism with reference counting pointer? I'd appreciate code samples cause obviously im doing something wrong here if I'm having this problem.

PS: Please don't tell me to use standard library with smart pointers because that's impossible at this moment.

Fairly obvious:

SP<DerivedClass> retPtr = new DerivedClass();

should be:

SP<BaseClass> retPtr = new DerivedClass();

You should add implicit converting constructor for SP<T> :

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

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

Why not add a template assignment operator:

template <class Base>
class SP
{
    ...

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

(and maybe copy constructor, too)?

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 will not know how to construct SP<BaseClass> from a SP<DerivedClass> ; for him, they are unrelated.

The conversion constructor is fairly trivial, since internally you can convert *DerivedClass to *BaseClass automatically. Code may be very similar to that for the copy constructor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM