"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > The Most Vexing Parse: Timer() - Object or Function Call?

The Most Vexing Parse: Timer() - Object or Function Call?

Published on 2024-12-21
Browse:735

The Most Vexing Parse: Timer() - Object or Function Call?

Most Vexing Parse: Unraveling Ambiguity in C 11

The "most vexing parse" ambiguity in C 11 presents itself when using uniform initializers, as evidenced in the following code snippet:

#include 

class Timer
{
public:
    Timer() {}
};

int main()
{
    auto dv = Timer(); // Ambiguity: Object or function call?
    int time_keeper(Timer()); // Ambiguity: Pointer or call?
    return 0;
}

Understanding the First Expression (auto dv = Timer())

In the first expression, the auto keyword implies that the type of dv is inferred from the initializer on the right side of the equal sign (=). The initializer is a call to the Timer constructor with no arguments, which returns a Timer object. Therefore, dv is an object of type Timer.

Understanding the Second Expression (int time_keeper(Timer()))

In the second expression, the ambiguity arises because the compiler cannot determine whether Timer() is a function call or an object of type Timer passed by reference.

  • If Timer() is a function call, then int time_keeper(Timer()) declares a function called time_keeper that takes a Timer object as input and returns an int.
  • If Timer() is an object of type Timer, then int time_keeper(Timer()) declares a function called time_keeper that takes a pointer to a Timer object as input and returns an int.

However, because functions decay to pointers when passed as arguments, the true type of time_keeper is int(Timer(*)()), which resolves the ambiguity in favor of the pointer-to-function interpretation.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3