Topic: Why 'operator->' requires return type to be a pointer?(addition)
Author: "Samuel Schulman" <s.schulman@berlin.de>
Date: Tue, 19 Jun 2001 12:17:02 GMT Raw View
"Samuel Schulman" <s.schulman@berlin.de> wrote in message
news:pThX6.4182$35.2694033@typhoon.san.rr.com...
> >
> >"Daniel Frey" <daniel.frey@aixigo.de> wrote in message
> news:3B2619B0.21B1CABD@aixigo.de...
> >Hello,
> >
> >Consider the following code:
> >
> >
> >
> >template< typename T > class oid // 'pointer' to a database object
> >{
> > ...
> >
> > T asObject() const // OK
> > {
> > return T( *this );
> > }
> >
> > T operator->() const // Not OK, T must be T*
> > {
> > return T( *this );
> > }
> >
> > ...
> >};
> >
> >
> > oid< X > x;
> >
> > cout << x.asObject().name(); // Works, but looks ugly.
> > cout << x->name(); // Doesn't work.
> >
> > cout << x.asObject().parent().asObject().owner().asObject().name(); //
> >Ouch...
> > cout << x->parent()->owner()->name(); // Yeah!
> >
> >
> >
> >Why is operator-> required (AFAIK) to return a pointer? Is there any
> >good reason I can't see? Was it considered to change (enhance) the
> >standard on that point? This shouldn't even break any existing code as
> >it only allows what's currently illegal.
> >
> >Regards, Daniel
> >
> >--
> >Daniel Frey
> >
>
> The standard does not require the operator to return type of pointer-to-T.
> As with the other operators, you usually want an operator, to behave like
> its
> built-in counterpart.
> The operator->() is used in other cases as well, where he does not return
> pointer-to-T but returns class type.
> But you should be aware of what you really want, and what the tradeoffs
are.
>
> In this line:
>
> cout << x->parent()->owner()->name(); // Yeah! (are you sure:))
>
> you will have three temporary objects created and destroyed, which means
you
> will have
> three times the constructor executed and three times the destructor
> executed, this can get expensive.
I forgott to mention, that on some compilers you are actually going to have
even
three more copy-constructors invoked.
So the total could be 9 function executions down the road.
> Therefore(as usual) be sure what you need, and what you will pay for it,
in
> the end .
>
> - Samuel
>
Regards,
Samuel
---
[ 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 ]