huh?!
has a message from me just disappeared?!
Im pretty sure that the thread went:
jabbah: Hi, I just found, ....
banfa: Here is the problem...
jabbah:ok, I understand....
banfa: That should work...
jabbah: I thought vector....
jabbah: < This Message Seems To Have Disappeard >
banfa: It doesn't matter...
can that be?! hm well
-------------------
regarding "plus one vs. times two"
ok, i agree that
avoiding doing it more than necessary is good for program efficiency.
however, im convinced, that reallocation is mandated to double the capacity. or maybe not neccessarily "double", ie increase by a factor of two, but still increase it by some constant factor. this must be in order to achieve "Constant amortized time", specifically
-
for( unsigned int i=0; i < M; ++i ){
-
v.reserve(i);
-
}
-
will not do more reallocations than log(M). So, as far as i understand it, the specification of vector ensures, that we dont do more reallocations than necessary. the _specification_ and not just some implementation!
------------------------------
now let me rewrite the message that i believe has been lost.
going back to the original problem: invalid reference due to reallocation.
I _do_ understand that the reference is invalid _after_ push_back, ie
-
const X& x = V[0];
-
V.reserve( ... );
-
cout << x; // illegal, because x may have been invalidated
-
but I do not understand why push_back( V[0] ) shouldnt work. consider the following implementation of push_back:
- push_back( const X& x ){
-
if ( enough capacity ) {
-
copy x
-
} else {
-
allocate new space
-
copy from old space to new space
-
copy x
-
deallocate old space
-
}
-
}
-
This would perfectly well work. its just a matter of the order of the last two lines of code.
_When_ exactly do i have to stop using references/ptrs/iters? certainly _after_ push_back has terminated, but why cant push_back itself not work with the reference that is valid at the point of calling push_back?
is the statement
" V.push_back( V[0] ) is undefined"
really standard conforming?
im insisting a) out of interest - i simply want to understand, but also b) out of despair - i have a similar situation where the V.reserve( ... ); prior to V.push_back() doesnt seem to be an option and i really dont feel like making an extra (unnecessary) copy