Boost Shared Ptr and reinterpret_cast

Started by
4 comments, last by ToohrVyk 16 years, 2 months ago
Hi! I want to cast shared pointers of completely different types. For instance shared_ptr<int> and shared_ptr<float>. Unfortunately there is no reinterpret_pointer_cast or similar, which could provide the functionality of reintepret_cast... Is there a way to do it anyway or is there a another way to cast these pointers?
Advertisement
If all you want is a float*, you can just do reinterpret_cast<float*>(intSP.get()). If you need a shared_ptr<float>, you can wrap the result of that in a new shared_ptr using a null deleter, and make sure the shared_ptr<float> doesn't outlive the original shared_ptr<int>. If you can't be sure of that, you could additionally hold a reference to the shared_ptr<int> inside the deleter for the shared_ptr<float>, which would work as long as you don't have extremely exotic circular reference stuff going on (you don't, in the case of ints and floats). But for God's sake, why? One doesn't generally mention the ugly hackishness of reinterpret_cast in the same sentence as the enlightened abstraction of shared_ptr. What are you doing?
Looking at the documentation, I can see it provides a:
 template<class Y> shared_ptr(shared_ptr<Y> const & r);


Have you tried it?
You should never do this, but if you want to convert a shared_ptr<int> to a shared_ptr<float> you can use:
  shared_ptr<int> a = /* something */;  shared_ptr<float> b = static_pointer_cast<float>(shared_ptr<void>(a));
Well, I wrote a small resource manager. To get a handle to a resource the developer must call ResourceGroup::getResource(string name) which should return a shared pointer. Since the needed data type could be anything the returned pointer holding an default type must be casted.

But I think I will create an empty class "Resource" from which each resource type can derive it's own resource class. Then I can use the base class as the underlaying data type for the shared pointer. I think that aproach is quite cleaner than the first ;)
Perhaps no elemntary data types are possible than, but that is not so important.

Nevertheless I will read something about those deleters. Sounds interesting.

Thank you for the fast answers :)
Quote:Original post by okoman
Well, I wrote a small resource manager. To get a handle to a resource the developer must call ResourceGroup::getResource(string name) which should return a shared pointer. Since the needed data type could be anything the returned pointer holding an default type must be casted.


Type parametrization? Why not simply intantiate the resource manager for every distinct type, and be done with it? This would also solve the hidden problem that you will encounter later on, which is that when you need to convert a resource-name to a texture, you can't afford having the resource-name load a mesh instead.

This topic is closed to new replies.

Advertisement