Home  >  Article  >  Backend Development  >  The Most Vexing Parse: Timer() - Object or Function Call?

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

Patricia Arquette
Patricia ArquetteOriginal
2024-10-31 18:09:01201browse

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:

<code class="cpp">#include <iostream>

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

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

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.

The above is the detailed content of The Most Vexing Parse: Timer() - Object or Function Call?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn