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::SmartPointer doesn'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::SmartPointer can only be used with ITK classes, or, more accurately, with classes which have Register() and UnRegister() methods. For example, descendants of itk::LightObject class which, according to documentation,
is the highest level base class for most itk objects. It implements reference counting ...
Therefore, my assumption that
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.
is incorrect, because temporary itk::SmartPointer will 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With