[ACCEPTED]-Is operator-> "chained" for pointers?-method-chaining

Accepted answer
Score: 23

C++98 standard §13.5.6/1 "Class member access":

An 27 expression x->m is interpreted as (x.operator->())->m for a class 26 object x of type T if T::operator-> exists and if the operator 25 is selected at the best match function by 24 the overload resolution mechanism (13.3).

What 23 this means in practice is that when x is 22 a pointer, you don’t get chaining; you 21 then just get the built-in operator-> (i.e. x->m with 20 x a pointer translates to (*x).m).

But when x is 19 an object of class type T, then you can get 18 the chaining effect. Because then the interpretation 17 as (x.operator->())->m can be that (x.operator->()) itself is an object of 16 some class, say class U. Whence the second 15 -> can be resolved as U::operator->, and so on, if the 14 result of that again is a class type object…

Like, in 13 your case, Foo::operator-> produces (a reference to) an 12 object of class Bar, which does define an operator->.

But 11 when operator-> returns a pointer, as e.g. std::auto_ptr<T>::operator-> does, then 10 it's just the built-in operator-> that's used.

In passing, the 9 chaining can be used to practically prevent 8 someone from using delete inappropriately. std::auto_ptr does 7 not do that. And I’ve never seen it 6 done.

But there was once a long discussion 5 thread over in [comp.lang.c++.moderated] about 4 how to prevent inadvertent delete of the raw pointer 3 managed by a smart pointer, and this was 2 one possibility that was discussed.

Cheers 1 & hth.

Score: 3

The reason your first example works is because 9 you returned a reference instead of a pointer. That 8 operator would normally be invalid except 7 in the case that it is overloaded. Therefore, the 6 compiler must execute the overloaded functions 5 down the chain. However, in the case of 4 auto_ptr you actually are returned a real pointer 3 and the default operator -> is invoked for regular 2 pointers.

Please see the Overloading operator -> question for more 1 details.

Score: 0

No, it is not possible for it to work. If 7 you could overload operator -> for string * you could make 6 it work. But operator -> already has a definition for 5 all pointer types. So, just like you can't 4 overload + for primitive numeric types, you 3 can't overload operator -> for any pointer type.

And 2 even if you could, how could the compiler 1 know when the recursion should end?

More Related questions