...
In any case, the behavior of the index operators is unchecked (no exceptiosn exceptions are thrown).
Non-Compliant Example
...
Code Block |
---|
string bs("01234567");
for (int i=0; i<100; i++) {
bs[i] = 'X';
}
|
This program does not typically raise an exception and is likely to crash.
Compliant Solution
Wiki Markup |
---|
The following compliant solution uses the {{basic_string at()}} method which behaves in a similar fashion to the index {{operator\[\]}} but throws an {{out_of_range}} if {{pos >= size()}}. |
Code Block |
---|
string bs("01234567"); try { for (int i = 0; i < 100; i++) { bs.at(i) = '\0'; } } catch (...) { cerr << "Index out of range" << endl; } |
...