0

I'm thinking in use a boost::object_pool, but the types of objects to store are all in the same hierarchy. My question is how do I need to store and use the pool to convert each object into the desired type.

My guest that store the ancestor as a type of the pool, then convert the returned object with a dinamyc cast to the proper type.

Is it an object pool the best alternative??

Need some orientation :) Thanks in advance

EDIT: All of you are right. I was thinking in the traditional casting newObj = (newType)oldObj. Sorry.

5
  • 1
    "But then, I'm generating a new object" What!? That's not the way dynamic cast works. Commented Jul 7, 2011 at 10:05
  • 1
    I don't think you are generating a new object with dynamic_cast. You're casting one pointer to an object into a pointer of another type of object. Commented Jul 7, 2011 at 10:05
  • 1
    I do not fully understand your scenario but I can say one thing: using dynamic_cast does not generate new objects. Commented Jul 7, 2011 at 10:07
  • Edited. I was thinking in old style cast Commented Jul 7, 2011 at 10:16
  • The 'old style' cast to a direct class type will create a new object but will not work as intended in the typical scenarios I imagine. That would be reverse slicing (stackoverflow.com/questions/274626/…). The old style cast to a pointer type will work most of the time just like a dynamic cast, creating no object either. Commented Jul 7, 2011 at 17:08

2 Answers 2

2

To store polymorphic objects, the idiomatic solution is to store pointers of a base class in a value based container.

Your current solution of storing polymorphic objects by value does not work because it suffers from slicing. The boost object pool is no more than a fancy allocator and deallocator, it does not provide polymorphism.

Sign up to request clarification or add additional context in comments.

Comments

1

boost::object_pool is primarily for allocating lots of objects of the same type. You shouldn't use them for object hierarchies.

3 Comments

And what would be a viable alternative? Thanks. It would be a good idea a factory and some object pools, each containing their our objects?
@Killrazor: It's hard to say what an alternative might be without knowing what your allocation pattern for these objects is. What were you doing with them that made you think an object pool was necessary to begin with?
What I'm doing is to put and to remove different kind of sprites into a set of objects called "layer". It could be an animated sprite or a text sprite, or a particle effect, so I don't want to waste time allocating sprites into a manager and casting it to the correct type. My idea is to make a factory that returns an instance of object of the correct type from the correct pool, so having a set of pools behind the factory seems good, at least apparently :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.