Home > Backend Development > C++ > body text

What\'s the Most Vexing Parse and Why Does It Happen in C 11?

Barbara Streisand
Release: 2024-11-01 10:55:30
Original
773 people have browsed it

What's the Most Vexing Parse and Why Does It Happen in C  11?

Understanding Uniform Initializers and the Most Vexing Parse

In C 11, uniform initializers provide a concise syntax for initializing objects and data structures. However, their usage can lead to potential ambiguity, known as the "most vexing parse."

Most Vexing Parse

Consider the following code snippet:

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

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

int main() 
{
    auto dv = Timer(); // What is Timer() ? And what type is dv?
    int time_keeper(Timer()); // This is a function right? And why isn't the argument " Timer (*) ()"?
    return 0;
}</code>
Copy after login

Analysis:

dv = Timer();

  • Timer() can be interpreted as either a function call or an object construction.
  • Because auto is used to declare dv, its type is deduced from the expression on the right-hand side.
  • If Timer() is interpreted as a function call, dv would be an int because Timer() isn't a function that returns an object.
  • However, if Timer() is interpreted as object construction, dv would be a Timer object.

int time_keeper(Timer());

  • Timer() is interpreted as creating a temporary Timer object.
  • The argument of time_keeper is a pointer to a function that returns a Timer and takes no arguments.
  • The function is implicitly converted to a pointer when passed as an argument.
  • Therefore, the type of time_keeper is int(Timer(*)()).

Conclusion:

In the "most vexing parse" scenario, the compiler attempts to infer the type and interpretation of an expression based on context and rules. By understanding how these rules apply, programmers can avoid ambiguity and write code with clear intent.

The above is the detailed content of What\'s the Most Vexing Parse and Why Does It Happen in C 11?. 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!