Make any class reference counted with inheritance?
In my new project I wish to (mostly for to see how it will work out) completely ban raw pointers from my code.
My first approach was to let all classes inherit from this simple class: template class Base { public: typedef std::shared_ptr ptr; };
And simple use class::ptr wherever I need a pointer.
This approach seemed suitable until I realized sometimes my objects wish to pass the 'this' pointer to other objects. Letting my objects just wrap it inside a shared_ptr won't do since then there could be two owners for the same pointer. I assume开发者_StackOverflow this is bad.
My next idea was to change the 'Base' class to implement reference counting itself, thus every instance of classes that inherits from 'Base' can only have one count.
Is this a good solution, are there any better and can boost and/or stl already solve this problem for me?
You may want to take a look at enable_shared_from_this.
On another note, when using shared_ptr
, you need to be aware of the possibility of circular references. To avoid this, you can use weak_ptr
. This means you will need some way to distinguish between the two of them, so simply having a typedef class::ptr
may not suffice.
精彩评论