As we knew, In order to avoid memory leak, we had better to use SmartPtr to managing the object instead of common pointer.
In most cases, it works very well.
Now I have encountered a problem, I tried my best to describe it more simply.
I have a base class:
class Base;
I have another two classes inherited from base class:
class Derive1 : public Base;
class Derive2 : public Base;
If I use raw pointer, I can implement polymorphic easily;
Base *pd1 = new Derive1();
Base *pd2 = new Derive2();
But If I want to use smartPtr
to implement the same thing how should I to do? For example:
SmartPtr<Base> pd1 = SmartPtr<Derive1>(new Derive1);
Is there smartPtr
to support the transformation, or shall I need to implement a template of smartPtr
, but If I implement the template by myself, how to avoid the code bloating,who has good advice?
If there is a template smartPtr supporting this operation, how do it accomplish this function? as we know a base pointer can point to a derived object, but it is bad in turn!!