tags:

views:

555

answers:

2

I'm in a situation where i must use a c style function that returns the len copied. I decided i should resize to max, then resize to the length returned http://stackoverflow.com/questions/605539/expand-size-of-vector-passed-as-memory

I know resize sets the value to fillValue (always 0?). So theres going to be pointless initialization (hopefully less then a mb each time) 60times every second. Is there a way ti disable the initiation on resize?

+4  A: 

Basically no. Elements in the vector are default constructed upon a resize (for an integer this results in 0).

Assuming you are using reserve() to ensure that resize() does not allocate memory I would not worry about this unless it proves to be a performance issue later on.

If you are concerned you may wish to consider just using a regular array and storing the item count in a separate variable. This will give you the best performance.

Update:

John asked:

Is the constructor really guaranteed to zero that memory? I thought that was undefined?

Yes and no. The primitive types (int, bool, float, etc) do have default constructors that initialize them to zero. However unlike regular classes or structs the compiler does not automatically call them.

E.g

int a;         // uninitialized
int b = int(); // initialized to 0

Because vector::resize uses the latter form when adding items you are guaranteed that the elements created will be correctly initialized to zero. This is true of all the STL collections that implicitly create elements.

Andrew Grant
Is the constructor really guaranteed to zero that memory? I thought that was undefined?
John Leidegren
Yeap, I've added an update explaining why
Andrew Grant
A: 

Assuming you are using reserve() to ensure that resize() does not allocate memory I would not worry about this unless it proves to be a performance issue later on.

So if this does prove to be a performance issue, how would you trick the vector not to initialize the memory.

Since the memory is written afterwards anyway, this is quite a performance issue

Is this a question?
GMan
yes :-) (just forgot a question mark)> how would you trick the vector not to initialize the memory?