[comp.lang.c++] operator&

fuchs@it.uka.de (Harald Fuchs) (11/01/90)

I tried to define a counted pointer class "Xptr" to another class "X"
and ran into a problem with the address-of "operator&". I redefined
this operator to return a counted rather than a normal pointer, but for
Xptr::operator-> () I need the real address of my X object (i.e. an X*
rather than an Xptr). Is there a way to access the "normal" address-of
operator even if it is redefined for a user-defined type?

    // Xptr.h

    #include "X.h"

    class Xptr {
      class Xrep {
        friend class Xptr;
        friend Xptr operator& (const X&);
        unsigned short ref;
        X obj;
        Xrep (const X& x): ref (0), obj (x) {}
        void deref () { if (!--ref) delete this; }
      };
      Xrep* p;
      static Xrep*const nil;
    public:
      Xptr (Xrep* x = 0): p (x ? x : nil) { p->ref++; }
      Xptr (const Xptr& x): p (x.p) { p->ref++; }
      ~Xptr () { p->deref (); }
      Xptr& operator= (const Xptr& x)
        { x.p->ref++; p->deref (); p = x.p; return *this; }
      operator char () const { return p != nil; } // Usage: if (cp) ...
      X& operator* () const { return p->obj; }
    //X* operator-> () const { return &p->obj; }  // This won't work
      X* operator-> () const { return (X*) ((char*) p + sizeof p->ref); }
        // Ugly hack: don't call operator& for an X
    };

    inline Xptr operator& (const X& x) { return new Xptr::Xrep (x); }
      // Usage: X obj; Xptr p = &obj;

    // Xptr.C

    #include "Xptr.h"

    static unsigned short null = 1; // Never deallocate
    Xptr::Xrep*const Xptr::nil = (Xptr::Xrep*) &null;

--

Harald Fuchs <fuchs@it.uka.de> <fuchs%it.uka.de@relay.cs.net> ...
<fuchs@telematik.informatik.uni-karlsruhe.dbp.de>   *gulp*

jgro@lia (Jeremy Grodberg) (11/06/90)

In article <fuchs.657417082@t5000> fuchs@it.uka.de (Harald Fuchs) writes:
<I tried to define a counted pointer class "Xptr" to another class "X"
<and ran into a problem with the address-of "operator&". I redefined
<this operator to return a counted rather than a normal pointer, but for
<Xptr::operator-> () I need the real address of my X object (i.e. an X*
<rather than an Xptr). Is there a way to access the "normal" address-of
<operator even if it is redefined for a user-defined type?
<    //X* operator-> () const { return &p->obj; }  // This won't work

try 
  X* operator-> () const { return ::operator&(p->obj); }

::operator&()  explicitly calls the global non-overloaded & operator.
-- 
Jeremy Grodberg      "I don't feel witty today.  Don't bug me."
jgro@lia.com