string::iterator should have more error checking
Frederick Virchanza Gotham
cauldwell.thomas@gmail.com
Thu Jun 23 21:05:22 GMT 2022
If a program is compiled with "-D_GLIBCXX_DEBUG", I would expect it at
runtime to catch the error on the last line in the following program:
#include <iostream>
#include <string>
#include <string_view>
#include <type_traits>
using namespace std;
int main(void)
{
cout << "string::const_iterator is "
<< (is_same_v< string::const_iterator, char const * > ? "just
a raw pointer" : "NOT a simple pointer") << endl;
cout << "string_view::const_iterator is "
<< (is_same_v< string_view::const_iterator, char const * > ?
"just a raw pointer" : "NOT a simple pointer") << endl;
string s("brush");
cout << string_view( &*(s.cbegin() + 1u), &*(s.cend() + 876u) ) << endl;
}
string::iterator is NOT a simple pointer -- it is a class and so we
can overload the following operators to catch errors:
(1) unary operator*
(2) binary operator+
(3) binary operator-
The error on the last line of the above program would be caught at
runtime if the iterator were written as follows:
class string {
class iterator {
char const *const p_min, *const p_max; // initialised in constructor
char *p;
public:
iterator &operator+(ptrdiff_t const n)
{
assert( p+n >= p_min );
assert( p+n <= p_max );
// more code here
}
};
};
Similarly the unary operator* could be overloaded to catch the error
when "end()" gets dereferenced.
More information about the Libstdc++
mailing list