Do I have to allocate everything on the heap (that gets stored within) heap containers?
I'm overriding the new operator to manually allocate heap space when using the new keyword.
Usually using a stack-allocated heap container with pointers to its items-
CArray<CObject*开发者_C百科> objects;
-is fine. but I'm picky and I want to make buffers-
CArray<CObject> objects;
-that let me modify POD types. So, I allocate them on the stack which is naturally suited for their use:
CVertex vertex;
objects.push_back(vertex);
But it corrupts the heap (I've had one of those bad weeks) and gives a crazy error:
0xC0000017: Not Enough Quota.
I pre-allocate the array objects and then use the = operator internally in push_back().
I solved the problem by allocating the temporary objects on the heap and then adding them to the array. But it doesn't seem right, and I just don't get it.
As requested, some code:
CArray::push_back( T& newElement )
{
m_internalElements[allocatedSize] = newElement;
allocatedSize++;
}
CArray::preallocate_and_initialize( size_t itemCount )
{
T* newInternalElements = mem::allocate_and_initialize( T, itemCount );
//copy over
}
Note that it all works with heap allocated CVertex's as I am using these objects in a binary search of the buffer elements (finding the right item in the index buffer for a given vertex) and it builds a mesh perfectly fine!
0xC0000017
is STATUS_NO_MEMORY
. I.e., you exhausted the virtual address space, i.e., you are using too much memory.
If you expect to have a lot of elements, reserving space before you call push_back
repeatedly should be enough to avoid running out of memory. You can use CArray::SetSize(0, itemCount)
to reserve space for all your elements.
CVertex is derived from CObject? You cant do that if CVertex has more instance data. (I mean you cannot create an array of CObjects and put CVertexes in it) How big should the compiler make the slots in the CObject array, they will be CObject sized, then you will try to put something bigger in the slots -> bang
You should put boost::shared_ptr objects in your array. Once you have that idiom worked out you will never go back
精彩评论