Topic: Is this code safe?


Author: "Joe Gottman" <joegottman@worldnet.att.net>
Date: Sat, 11 Aug 2001 17:40:02 GMT
Raw View
"John Harrison" <jahhaj@bigfoot.com> wrote in message
news:G63d7.27624$e%3.3229578@news2-win.server.ntlworld.com...
>
> "Joe Gottman" <joegottman@worldnet.att.net> wrote in message
> news:wU%c7.4530$Ki1.330076@bgtnsc06-news.ops.worldnet.att.net...
> >   Suppose I have a class Foo with a pair of member functions like the
> > following:
> >
> >     class MyClass {
> >           ...
> >            iterator getIterator(); // iterator into some sort of STL
> > container
> >            const_iterator getIterator() const; //Same function, only
> it
> > returns a const_iterator
> > };
> >
> > I want to ensure that the two versions of getIterator do the same
> thing,
> > with the only difference being the return type.   Is it safe to define
> the
> > const version as follows, assuming that the non-const version makes no
> > changes to the container or any of its elements?
> >
> > Foo::const_iterator Foo::getIterator() const
> > {
> >     //Cast away constness, then call non-const version
> >     Foo * non_const_this = const_cast<Foo *>(this);
> >
> >    //Use automatic conversion from iterator to const_iterator
> >     return non_const_this->getIterator();
> > }
> >
> > If this is not safe, is there any safe way to define one function in
> terms
> > of the other so as to avoid repeating code?
> >
> > Joe Gottman
> >
>
> Yes it is safe.
>
> In C++ is illegal to attempt to modify an object declared const.
> Obviously using const_cast makes this more likely to happen but if
> you're sure that it isn't going to happen then using const_cast is safe.
>


   Thanks.  Does the standard say anything about whether the non-const
versions of any of the following STL member functions are guaranteed not to
change the container?
       begin(), end(), rbegin(), rend(), (for all containers)
       front(), back() (for vectors, deques, & lists)
       operator[](), at() (for vectors and deques, NOT maps)
       find(), lower_bound(), upper_bound(), equal_range() (for associative
containers)
        iterator::operator*(), iterator::operator->() (for all containers)

There's no reason I can see why they should change the container, since they
are all used just to get a handle into it.  If I know they don't change the
container, then I can easily guarantee that my own code will not modify any
element inside the container.

Joe Gottman

---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.research.att.com/~austern/csc/faq.html                ]