Specifically considering the C++ string
class constructor spec, we have:
string (const string& str, size_t pos, size_t len = npos);
string (const char* s, size_t n);
which are essentially of the same form/intent, excepting string vs. c-string. The exception specification however is very different:
If pos is greater then str's length, an out_of_range exception is thrown.
If n is greater than the array pointed by s, it causes undefined behavior.
I wonder why this is? Performance aside, when is it a good idea to throw an exception vs. permitting "undefined behavior"? The answer would seemingly depend on the following:
The difference in the two cases is simply that in the first one, it is possible for the implementation to check if there is an error in the parameter passed, while in the second one it is impossible (there is no way of checking which is the length of the string, since only a pointer is passed).
So the general rule could be the following:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With