Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I call operator() on temporary objects directly?

What I want to do can be summarized into the following code:

struct A{};

struct B{
    A& a;
    B(A& a) noexcept : a(a){}
    int operator()(int) {}
};

int main(){
    A a;
    B(a)(2);
}

And my compiler (g++ 6) rejected the code complaining that a shadows a parameter. However, if I try to explicitly call operator(), it works as expected.

It seems that g++ will ignore the parentheses and see the statement as a declaration.

Is this the specified or expected behavior?

like image 305
YiFei Avatar asked Jan 12 '17 10:01

YiFei


People also ask

How do you call an operator in C++?

The function call operator is denoted by “()” which is used to call function and pass parameters. It is overloaded by the instance of the class known as a function object. When the function call operator is overloaded, an operator function is created that can be used to pass parameters.

What is a temporary object in C++?

A temporary object is an unnamed object created by the compiler to store a temporary value.

What is the use of function call operator?

The function call operator, when overloaded, does not modify how functions are called. Rather, it modifies how the operator is to be interpreted when applied to objects of a given type.


1 Answers

This is one of those icky parsing rules which catches you every now and again. As you suggest, B(a)(2); is actually equivalent to B a(2);, so your code tries to initialize a B with an int.

To fix this, you can use C++11's uniform initialization:

B{a}(2);
like image 138
TartanLlama Avatar answered Nov 01 '22 12:11

TartanLlama