Jack wrote:
>
>> Have you seen the boost pointer containers? I think they will solve
>> your problem.
>> http://www.boost.org/libs/ptr_contai...container.html
>>
>> A ptr_array (statically sized) does pretty much what you want, I think.
>> The only thing missing is allocation-in-one.
>>
>> I haven't checked this will work, but perhaps you could allocate a B
>> array, and then use ptr_array::replace to make it's pointers point to
>> the objects in your array.
>
> No. ptr_array::replace handles only single elements, so this is just one
> more variation of the "multiple calls to new" solution.
....not if you preallocate the array, and replace the pointers... It's
one call to new and a bunch of pointer assignments
>> You know what? Get it working first. If the x news are too slow, then
>> try new [x].
>
> Yes, trying should always be done before code optimization process. In this
> case there will be tens of thousands of objects, so it is pretty obvious
> that new[] will be more efficient. Generally, when you have to handle
> multiple small objects the memory pool idiom should be used. The solution
> presented by Jakob Bieling resembles that idiom, but its weakness is the
> type unsafety.
Providing your own allocator and/or operator new for the derived type
could certainly help.
> I am thankful for your trying to help. But even better solutions will be
> welcome
OK, last ditch attempt
You seem to think that you cannot provide Buffer, templated on the
derived type to the user. I'm not sure this is the case, but I'll have
to accept your word on that.
The fundamental problem then, is knowing the size of the array to be
deallocated. If you know the size of an element (pretty sure you cannot
to that polymorphically, i.e., you need to know the derived type, or at
least sizoef(b)), you can allocate a block of memory, and call placement
new for each element.
In the destructor, you can call the destructor of each element in the
array, and then delete the block you allocated.
What that gains you over over providing the derived type in the
template, is that it is run time. A call to the constructor might look
like:
Buffer b<A>(sizeof(B), 5);
I see no way around requiring the derived type *somewhere*.
Ben Pope
--
I'm not just a number. To many, I'm known as a string...