public inbox for libstdc++@gcc.gnu.org
 help / color / mirror / Atom feed
* string::iterator should have more error checking
@ 2022-06-23 21:05 Frederick Virchanza Gotham
  2022-06-23 21:26 ` Jonathan Wakely
  0 siblings, 1 reply; 9+ messages in thread
From: Frederick Virchanza Gotham @ 2022-06-23 21:05 UTC (permalink / raw)
  To: libstdc++

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.

^ permalink raw reply	[flat|nested] 9+ messages in thread

end of thread, other threads:[~2022-06-24 11:14 UTC | newest]

Thread overview: 9+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2022-06-23 21:05 string::iterator should have more error checking Frederick Virchanza Gotham
2022-06-23 21:26 ` Jonathan Wakely
2022-06-23 22:01   ` Frederick Virchanza Gotham
2022-06-23 22:35     ` Jonathan Wakely
2022-06-24  9:06       ` Frederick Virchanza Gotham
2022-06-24  9:35         ` Jonathan Wakely
2022-06-24 10:10           ` Frederick Virchanza Gotham
2022-06-24 10:28             ` Jonathan Wakely
2022-06-24 11:14               ` Frederick Virchanza Gotham

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).