about resizing vectors...

L

Lasse Skyum

Is it true that when std::vector resizes for more capacity it copies all the
elements to a bigger array and then destroys all the elements from the old
one?

If so, why doesn't it just use realloc for possible resizing of the existing
memoryblock??
 
H

Howard Hinnant

Lasse Skyum said:
Is it true that when std::vector resizes for more capacity it copies all the
elements to a bigger array and then destroys all the elements from the old
one?
Yes.

If so, why doesn't it just use realloc for possible resizing of the existing
memoryblock??

The most fundamental reason is that in general vector's contained
element can not be copied using memcpy (as realloc threatens to do).
Instead the element's copy constructor must be used.

That being said, I believe it is a worthwhile goal to teach vector to
attempt to expand in place when it needs to increase its capacity.

-Howard
 
R

Rolf Magnus

Lasse Skyum said:
Is it true that when std::vector resizes for more capacity it copies
all the elements to a bigger array and then destroys all the elements
from the old one?
Yes.

If so, why doesn't it just use realloc for possible resizing of the
existing memoryblock??

Realloc basically does the same, but would only work correctly with POD
types, since it's not aware of classes and their copy constructors and
destructors.
 
L

Lasse Skyum

The most fundamental reason is that in general vector's contained
element can not be copied using memcpy (as realloc threatens to do).
Instead the element's copy constructor must be used.

Okay, I understand...
That being said, I believe it is a worthwhile goal to teach vector to
attempt to expand in place when it needs to increase its capacity.

Yes, but nevermind... I'm just studing how it's all working and don't really
need to optimize this :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,526
Members
44,997
Latest member
mileyka

Latest Threads

Top