I am using C++. C++0x using Visual Studio 2010 to be correct.
Suppose I have a class Z. To make it safer in my application to work with pointers to this class, I can consistently use smart pointers (shared pointer, weak pointer).
Now this class Z inherits from a class X. Some parts of my application will work with pointers to class X, others will work with pointers to class Z.
- Can I still use smart pointers?
- Do shared pointers still work if I have some that refer to X and others that refer to Z? Is it guaranteed that the destruction of the last shared pointer to the instance (regardless of whether it is
std::shared_ptr<X>
orstd::shared_ptr<Z>
) deletes the instance? Am I sure that if I deletestd::shared_ptr<X>
, that the instance is kept as long as there is anotherstd::shared_ptr<Y>
?
Now suppose that I use multiple inheritance, where Z inherits from classes X and Y.
Some parts of my application will work with std::shared_ptr<X>
, others with std::shared_ptr<Y>
and others with std::shared_ptr<Z>
.
- Can I still use shared pointers this way?
- Is it still guaranteed that only the last smart pointer (regardless of whether it points to X, Y or Z) deletes the instance?
By the way, how can I safely cast one smart pointer to another, e.g. cast std::shared_ptr<Z>
to std::shared_ptr<X>
? Does this work? Is this allowed?
Notice that I explicitly refer to non-intrusive pointers (as the new std::shared_ptr
and std::weak_ptr
in C++0x). When using intrusive pointers (like in Boost), it probably works since the instance itself is responsible for keeping the counter.