tags:

views:

60

answers:

2

Consider the following code:

typedef std::vector<int> cont_t; // Any container with RA-iterators
typedef cont_t::const_iterator citer_t; // Random access iterator

cont_t v(100);
const int start = 15; // start > 0.
citer_t it = v.begin() - start; // Do not use *it

int a1 = 20, b1 = 30; // a1, b1 >= start
int a2 = 30, b2 = 40; // a2, b2 >= start

int x = std::min_element(it + a1, it + b1); // 
int y = std::min_element(it + a2, it + b2); //
int z = std::min_element(it + 15, it + 25); //
...

Is it possible to use the random access iterator it out of range?

+3  A: 

You'll get assertion condition here according to C++ Standard 24.1.5 Table 76.

Kirill V. Lyadvinsky
Only in debug mode I guess ?
Matthieu M.
Standard doesn't states anything about debug mode.
Kirill V. Lyadvinsky
The table states the precondition that's being violated. It's entirely up to the implementation whether it checks or assumes the preconditions.
Mike Seymour
I prefer to consider the worst(nuclear explosion?) when something depends on the implementation.
Kirill V. Lyadvinsky
But your answer describes the *best* possible scenario. Not a nuclear explosion, but a nice clean error message.A more correct answer would be that it's not allowed, and there's no guarantee of what'll happen if you try it.
jalf
"Assertion condition" means that it is not allowed. Isn't it?
Kirill V. Lyadvinsky
@Kirill: Yes, but "not allowed" doesn't necessarily mean "assertion".
sbi
+5  A: 

It's certainly possible to write code that trys to use an out-of-range iterator. Running the code will give undefined behaviour. Depending on the library implementation, it may throw an exception, access random bits of memory, trigger a protection fault, or initiate a thermonuclear explosion in your CPU.

Mike Seymour
I doubt the thermonuclear explosion. Not enough initial mass.
Konrad Rudolph
@Konrad Rudolph, It depends on CPU model.
Kirill V. Lyadvinsky