Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling Out-of-Range Indices

Tags:

c++

oop

exception

For a container class, what should the expected behavior be when the user of the class tries to set a value that's outside the class's size?

The method in question is a "replace" method (like operator[]), rather than an "add" method (like operator+=).

I could throw an out_of_range exception or I could just resize the container to accommodate the addition.

like image 256
Maxpm Avatar asked Jan 29 '26 16:01

Maxpm


1 Answers

An out of range exception is more appropriate here because "replace" semantics normally means that the caller is presuming/asserting there is data at the specified index, which there is not.

like image 179
kvista Avatar answered Jan 31 '26 07:01

kvista



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!