开发者

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜