I'm looking for something like std::static_pointer_cast, std::const_pointer_cast, and std::dynamic_pointer_cast for std::shared_pointer.
I tried ITK's documentation and itk::SmartPointer's source code and found nothing about smart pointer casting.
In one particular case I needed to add 'constness' to a pointer (convert itk::SmartPointer<T> to itk::SmartPointer<const T>) in order to pass it to a third-party function. Passing a raw pointer is out of the question because data will be deleted once the automatically created const smart pointer goes out of scope.
The only relatively safe solution I found:
static_cast<itk::SmartPointer<const T>>(itk_smart_pointer_of_t).
I don't know whether this approach is thread-safe or has other possible pitfalls. Moreover, in case of dynamic_cast things will get even messier.
It seems strange that ITK doesn't have native std::const_pointer_cast-like and other casts.
TL;DR:
itk::SmartPointerdoesn't need pointer casts, just cast the "raw" pointer and re-wrap it instead.ITK smart pointers use intrusive reference counting, meaning that the owned object must provide the reference counter.
itk::SmartPointercan only be used with ITK classes, or, more accurately, with classes which haveRegister()andUnRegister()methods. For example, descendants ofitk::LightObjectclass which, according to documentation,Therefore, my assumption that
is incorrect, because temporary
itk::SmartPointerwill just increase and then decrease owned object's reference counter.This means it is safe to pass a "not-so-raw" pointer to a function accepting a smart pointer, or to create temporary smart pointer manually and pass it to the function.