Re: Wrong
Joshua Maurice wrote:
On Apr 17, 12:49 pm, "Leigh Johnston" <le...@i42.co.uk> wrote:
A certain regular of this newsgroup thinks the following code is not
wrong, discuss.
void foo()
{
std::vector<int> v;
v.reserve(2);
v.push_back(41);
*(&v[0]+1) = 42;
}
The actual definition of "wrong" may vary from individual to individual
as does common sense so it seems.
This may help:
If by wrong, you mean undefined behavior, then yes. The push_back is
fine, but the next line writes to an area which has been reserved but
not in the size.
a) Huh? At
*(&v[0]+1) = 42
the size is already 1, because of the previous push_back. So, I don't see a
write to something not in the size.
I know of several debug implementations of the
standard library which will crash horribly and report the error of the
code.
That would be interesting. Even replacing 1 by 2:
*( &v[0] + 2 ) = 42
I am aware only of implementations that would catch v[2] = 42. The &v[0]+2
is effectively bypassing the library implementation since &v[0] returns a
plain pointer, which then is subject to ordinary pointer arithmetic. If an
implementation catches an out-of-bounds error here, it would not be because
of the way the _library_ is implemented.
Also: the pointer arithmetic is actually not out of bounds.
Upshot: I don't see undefined behavior in the code.
Best
Kai-Uwe Bux