out_of_range exception and subscript operator

S

subramanian100in

For vector and deque, the 'at( )' member function throws out_of_range
exception if the argument to the 'at( )' function is not in range. But
the subscript operator [ ] does not throw this exception for the same
situation.

My question:
Why can't the subscript operator [ ] itself throw the out_of_range
exception in which case the 'at ( )' member function may not be
needed ?

Kindly explain

Thanks
V.Subramanian
 
?

=?ISO-8859-1?Q?Erik_Wikstr=F6m?=

For vector and deque, the 'at( )' member function throws out_of_range
exception if the argument to the 'at( )' function is not in range. But
the subscript operator [ ] does not throw this exception for the same
situation.

My question:
Why can't the subscript operator [ ] itself throw the out_of_range
exception in which case the 'at ( )' member function may not be
needed ?

Because sometimes you can be sure that the index provided will be in
range and don't want the extra overhead associated with the check, the
operator[] is meant for occasions where you know that the code is safe
and you want as much performance as possible.
 
J

James Kanze

For vector and deque, the 'at( )' member function throws out_of_range
exception if the argument to the 'at( )' function is not in range. But
the subscript operator [ ] does not throw this exception for the same
situation.
My question:
Why can't the subscript operator [ ] itself throw the out_of_range
exception in which case the 'at ( )' member function may not be
needed ?

Because that's usually not what you want. You want some sort of
implementation defined crash, the equivalent of an assertion
failure. Undefined behavior allows the implementation to
provide this (and also allows removing the checks, if you find
that they create too much runtime overhead).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,773
Messages
2,569,594
Members
45,120
Latest member
ShelaWalli
Top