简体   繁体   中英

reallocating memory in efficient way

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.

您可以使用对象池或内存竞技场之类的自定义分配器,在其中从堆中预分配块,然后根据自定义策略将其分配出去。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM