user478571
user478571

Reputation:

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 ?

Upvotes: 0

Views: 588

Answers (4)

Howard Hinnant
Howard Hinnant

Reputation: 218700

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.

Upvotes: 1

Puppy
Puppy

Reputation: 146910

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.

Upvotes: 1

CashCow
CashCow

Reputation: 31435

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.

Upvotes: 3

Asha
Asha

Reputation: 11232

Use std::vector<Object>. It will do this automatically for you.

Upvotes: 9

Related Questions