Bernard Chen wrote:
Hello,
I was looking at the casting functions and the one that had the behavior I wanted most was the shared_polymorphic_cast. I do not want an empty shared_ptr<T> to be created if the cast cannot be performed. I would prefer to have an exception thrown in debug mode and release mode. The problem is that while going through the shared_ptr.hpp, I found a comment on line number 388 just above all the cast conversion functions "// shared_*_cast names are deprecated. Use *_pointer_cast instead." I have not found a *_pointer_cast function that does what I want. The dynamic_pointer_cast does not throw an exception. Is there a good alternative?
shared_polymorphic_cast is not part of the Library Technical Report:
http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2005/n1745.pdf
so, even though it's not likely to go away, you should probably not use it
if you are going to migrate to std::tr1::shared_ptr when it becomes
available for your compiler/STL.
One alternative is to write a simple wrapper over dynamic_pointer_cast and
use that instead. Of course in situations where you don't need a shared_ptr
you can use dynamic_cast
Should I enforce a standard on my team of using dynamic_pointer_cast along with a run-time check of seeing if an empty shared_ptr<T> was created?
Not a bad idea, because you can throw an exception that better describes the situation instead of the generic bad_cast. The idiomatic way to use dynamic_pointer_cast is if( shared_ptr<T> pt = dynamic_pointer_cast<T>( pu ) ) { // use pt } else { // handle failure }