Re: Why doesn't this code generate an inaccessible memory-error?
On 8 Feb., 14:35, Seungbeom Kim <musip...@bawi.org> wrote:
CornedBee wrote:
On Feb 6, 10:19 pm, "Martin B." <0xCDCDC...@gmx.at> wrote:
Wait. Hmm. std::vector::operator[] is *allowed* to throw a std::exception?
Using [] with an invalid index is UB, so it is allowed to do whatever
it wants.
It's just a very bad idea for an implementation to do that, IMO.
Control flow should never differ between compilation modes, i.e. a
function that cannot throw an exception in release mode shouldn't do
so in any other mode either.
Can you elaborate on this? The standard doesn't deal with the concept of
'compilation modes', but control flow can certainly differ between
different conditional inclusions or anything that depends on them.
A program using assert() can obviously have different control flow
between 'Release' and 'Debug' builds, and that is the desired behaviour.
On the same ground, I don't see anything wrong with a conditionally-
throwing implementation such as:
template<typename T, ...>
T& vector<T>::operator[](size_type i)
{
#ifndef NDEBUG
if (i >= size_) throw bad_index();
#endif
return data_[i];
}
Sinced I agree with CornedBee, let me give you my opinion. First, we
agree that behavior or program flow can change depending on what files
are included. But the change is of a different type. For a conditional
include, this could be because you compile for different environments
- and this change is requested by and controlled by the programmer.
For the assert case, the removal of the assert is made in confidence
that there will be no change to the behaviour of the program. The
assert is removed simply because it is assumed not to trigger.
Now returning to your example, your operator[] changes the
functionality in an unexpected way. There was no intention of the
programmer to change the program flow. Imagine a program using both
checked and unchecked access: it would assume that any exception would
not be from the operator[] and the failure might very well remain
undetected in spite of lots of checks in the test-code.
Another factor (probably a more important one) is that the programs
state was corrupted. Continuing a corrupted program is always a bad
idea.
/Peter
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]