Re: boost alternative to realloc
Alf P. Steinbach wrote:
* Kai-Uwe Bux:
Leigh Johnston wrote:
"Alf P. Steinbach" <alfps@start.no> wrote in message
news:hqcu3t$7lo$1@news.eternal-september.org...
<snip>
Unless I am mistaken you are basically advocating that the following
code is correct according to the standard:
void foo()
{
std::vector<int> v;
v.reserve(2);
v.push_back(41);
*(&v[0]+1) = 42;
}
The above code is plain wrong.
Please define your terms: what do you take "correct" to mean, and what is
"plain wrong"? Does the code have UB according to the standard?
If I you disagree then your position is
untenable. Anyone with an once of common sense would use std::vector in
the ways it was designed for and not abuse it like you are suggesting.
Keep the context in mind: Alf was pondering this option in the context of
the OP's request: If the alternative is to use malloc(), free(), and
realloc() manually, why not use the above? Or, why not do something like
the above inside the implementation of a little wrapper that, to the
outside, looks like the wrapper for malloc(), free(), and realloc() that
the OP was looking for?
Well, I was pondering this not in the context of the OP's request but in
the context of Leigh's explanation for his statement
"A combination of reserve() and a custom allocator whose construct is a
no-op might work although std::vector will probably still emit a construct
loop."
namely
"I meant so say resize() but said reserve() as I was thinking about
malloc/realloc. It is UB to access the allocated but uninitialized parts
of a std::vector."
There's no UB for writing to and subsequently reading those parts when the
element type is POD. It's just a raw array. And it's guaranteed there.
Sorry, I realized that soon after I posted and I was about to write a
retraction. But you stepped in before.
On the other hand, in the context of the OP's request, I don't think that
there's any guarantee that reserve() won't touch all parts of the buffer
by e.g. zeroing, and that could transform it from virtual address space to
actually allocated memory, but with a quality implementation that would be
unlikely.
Another thing, I wondered about are the guarantees of reallocation. If you
want std::vector<> to emulate realloc(), you might try:
std::vector< int > v;
v.reserve( 100 );
int * array = &v[0];
// realloc:
v.reserve( 200 ); // hm...
Off hand, I don't see a way to make sure that the first 100 elements will be
copied.
So for implementing the wrapper class the OP was looking for, this won't do
either.
Best
Kai-Uwe Bux