Home > Backend Development > C++ > body text

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

Patricia Arquette
Release: 2024-10-31 18:09:01
Original
200 people have browsed it

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!