0

Is the calling of an operator function similar to a normal function call? When a function call is encountered, its local variables, parameters, and the return address is loaded on to the call stack. Does this happen when we use an operator? If it happens, then the operator function should be removed from the stack after the execution is finished, right? Well, some part of me says that it doesn't happen that way because we're returning a reference to a local object, which will be destroyed after the execution is finished. I just want to know the details of it.

#include <stdio.h>
class OUT
{};

OUT & operator<<(OUT & out, int x)
{
printf("%d",x);
return out;
}    

int main()
{
OUT print;
print<<3<<4;   
}

1 Answer 1

2

Yes, a use of an overloaded operator function is semantically a function call.

[over.match.oper]/2 in the C++ Standard says, emphasis mine:

If either operand [in an operator expression] has a type that is a class or an enumeration, a user-defined operator function might be declared that implements this operator or a user-defined conversion can be necessary to convert the operand to a type that is appropriate for a built-in operator. In this case, overload resolution is used to determine which operator function or built-in operator is to be invoked to implement the operator. Therefore, the operator notation is first transformed to the equivalent function-call notation as summarized in Table 12 ....

So the Standard rules about object lifetimes apply in exactly the same ways. There's also no reason a compiler's manipulation of behind-the-scenes things like a call stack would need to be different.

Your example is fine not because there's something special about operator functions, but because it doesn't return a reference to a local object. In return out;, out names the function parameter with reference type, so it refers to some other object from outside of the function scope. In this case, out refers to the variable print in main, and the lifetime of print goes to the end of main.

Sign up to request clarification or add additional context in comments.

2 Comments

OUT & operator<<(OUT & out, int x) { OUT output; printf("%d",x); return output; } I tried making an object of type OUT; it was working, though the compiler showed the warning.
A reference to object past its lifetime isn't by itself invalid. Using a member of it would be -- but it has no members other than implicit member functions. And remember "working" doesn't mean "correct": when a program has undefined behavior, there are no guarantees about what will happen, so one possibility for what actually happens is exactly what someone wanted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.