This is the mail archive of the
gcc@gcc.gnu.org
mailing list for the GCC project.
Re: constness
- To: egcs at cygnus dot com
- Subject: Re: constness
- From: Nathan Myers <ncm at cygnus dot com>
- Date: Wed, 03 Jun 1998 17:25:56 -0700
- Newsgroups: cygnus.egcs
- Organization: http://www.cantrip.org/
- References: <199806031939.MAA09696.cygnus.egcs@paradigm.webvision.com>
dave madden wrote:
>
> I'm working on a ref-counted, copy-on-write smart pointer class tree,
> and I've encountered a problem with const handling. ...
> The problem is, it looks like the operator->() selected by egcs++ and
> g++ is chosen based on the constness of the smart pointer, and not the
> constness of the RealObject method being invoked:
>
> Ptr a;
> const Ptr b;
>
> a->const_function( ); // calls non-const operator->()
> b->const_function( ); // calls const operator->()
>
> Is there any way to structure the classes so that the non-const
> operator->() is only called when the method to be called through
> that pointer is also non-const? Is this the way the standard says
> it's supposed to be?
This is correct behavior, per the standard.
It is not sufficient to have a single type Ptr; you also need
a PtrToConst for pointing at const objects, and its operator->
returns a pointer to const. This PtrToConst type can be a
(partial) specialization:
-------------
template <class T> struct Ptr { T* operator->(); };
template <class T> struct Ptr<const T> { T const* operator->(); };
struct A { int i; };
int main()
{
Ptr<A> pa;
pa->i = 0; // OK
Ptr<const A> pca;
pca->i = 0; // error, pca->i not an lvalue.
}
------------
Generally, when I find myself starting to define a smart pointer
I try to reconsider how badly I want pointer semantics. Usually I
choose to replace what would have been the smart pointer with the
"actual object", as seen by users, and then (if appropriate) define
reference-copy semantics for these objects. The things pointed to
disappear from the interface and become implementation artifacts.
This gets away from the operator overloading issues, and allows
you to use the built-in const machinery directly.
Nathan Myers
ncm@cygnus.com