Smart pointers and polymorphism

放肆的年华 提交于 2019-12-11 03:04:35

问题


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.


回答1:


Fairly obvious:

SP<DerivedClass> retPtr = new DerivedClass();

should be:

SP<BaseClass> retPtr = new DerivedClass();



回答2:


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;
}



回答3:


Why not add a template assignment operator:

template <class Base>
class SP
{
    ...

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

(and maybe copy constructor, too)?




回答4:


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.



来源:https://stackoverflow.com/questions/2682557/smart-pointers-and-polymorphism

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!