Home > Enterprise >  Why can I use scalar type as the return type of operator->?
Why can I use scalar type as the return type of operator->?

Time:01-20

From cppreference:

The overload of operator -> must either return a raw pointer, or return an object (by reference or by value) for which operator -> is in turn overloaded.

However, I tested the following example, and it is accepted by GCC, Clang and MSVC:

struct A {
  int operator->();
};

According to cppreference, the return type int is neither a pointer nor a type that overloads operator->.

Why is this example correct? Where is this situation described in the standard? What is the intent of the standard to allow this?

CodePudding user response:

While the standard doesn't directly place restrictions on the return type of operator->, it does describe what happens when the overloaded -> operator is used:

12.6.5 Class member access [over.ref]

A class member access operator function is a function named operator-> that is a non-static member function taking no parameters. For an expression of the form
    postfix-expression -> template(opt) id-expression
the operator function is selected by overload resolution (12.4.1.2), and the expression is interpreted as
     ( postfix-expression . operator -> () ) -> template(opt) id-expression.

So when using your class, you can call the overloaded operator like a normal function by writing a.operator->(). But if you attempt to use the operator with a->name, this is interpreted as (a.operator->())->name which won't compile because it attempts to use -> on an int.

  •  Tags:  
  • Related