Using const_pointer_cast<T>(..)
This is a quick demonstration of const_pointer_cast<T>(..).
# include <boost/shared_ptr.hpp>
using boost::shared_ptr;
using boost::const_pointer_cast;
struct test_type { };
// Make an object and give it to a shared_ptr.
shared_ptr< test_type >
sp_non_const(
new test_type);
// Copy the shared_ptr to another, except the
// new shared_ptr holds a pointer to a const.
// This copy can be an implicit cast.
shared_ptr< test_type const >
sp_const(
sp_non_const);
// Copy the shared_ptr to a const to another
// shared_ptr, one that holds a non-const
// pointer. This is not an implicit cast.
// This is what const_pointer_cast is for.
shared_ptr< test_type >
sp_non_const2(
const_pointer_cast< test_type >( sp_const));
And there you have it. const_pointer_cast<T>(..) is used to cast away the const (or volatile) buried inside a smart pointer. It works with shared_ptr<T>s, intrusive_ptr<T>s, and raw pointers. Without it you would have to resort to reinterpret_cast<T>(..) to cast away const buried inside a shared_ptr<T> unless it provided ->shared_from_this().
Comments
Leave a Reply