A new, presumably larger block, can be obtained and initialized with the old block, and then the old block be freed.
purpose of that code ; reallocating the old memory area with new size
typeName is Object
Object *oldArray = objects ; // objects is pointer to old data block
objects = new Object[ newCapacity ] ;
for ( int k = 0; k < theSize ; k++ )
开发者_如何转开发 objects [k] = oldArray [k] ;
... // some other thing
delete [] oldArray ;
Are there any other way to do that job, efficiently ?
Use std::vector<Object>
. It will do this automatically for you.
The first thing you need to ask yourself is do you need to reallocate at all. Do you need a contiguous buffer?
Yes, std::vector
will implement it for you but if you don't actually have to have a contiguous buffer you can use std::deque
which will not reallocate and will potentially use our memory resources more efficiently.
The next thing you should consider is the cost of copying the objects compared to swapping them. That depends totally on the implementation of your objects. (If a swap requires 3 assignments it is obviously not as efficient, but if copies are deep it is likely that swap is more efficient).
Note: std::deque
will not reassign at all so no need to worry about it if this is what you are using.
You can use custom allocators like object pools or memory arenas, where you pre-allocate chunks off the heap and then divide them out according to a custom strategy.
To answer your question, yes this operation can be made more efficient. When this logic migrates to C++0x, it can be made vastly more efficient for many important use cases. vector
encapsulates this logic, and the most efficient techniques. Is your quest to learn how vector does it? If so, ask that, and I'd be happy to explain.
精彩评论