Home > Backend Development > C++ > body text

When Does C Uniform Initialization Become the \'Most Vexing Parse\'?

DDD
Release: 2024-11-01 21:37:29
Original
1048 people have browsed it

When Does C   Uniform Initialization Become the

Understanding the "Most Vexing Parse" Ambiguity in C Uniform Initializers

The "most vexing parse" refers to an ambiguity that can arise when using uniform initialization syntax in C 11. This ambiguity occurs when it is unclear whether a code expression is initializing an object or calling a function that returns an object.

To illustrate this ambiguity, consider the following code:

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

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

int main() 
{
    // Case 1: Initializing an object
    auto dv = Timer();

    // Case 2: Calling a function
    int time_keeper(Timer());

    return 0;
}</code>
Copy after login

Case 1: Initializing an Object

In the first case, auto dv = Timer() initializes an object of type Timer called dv. The type of dv is inferred as Timer because we are using auto to declare it.

Case 2: Calling a Function

In the second case, int time_keeper(Timer()) declares a function called time_keeper that returns an int and takes as its argument a pointer to a function that returns a Timer and takes no argument.

The reason why the argument is not Timer (*) () is that functions decay to pointers when passed as an argument. Therefore, the type of time_keeper is actually int(Timer(*)()).

This ambiguity can be avoided by explicitly specifying the type of the variable being initialized or declaring the function's signature explicitly. For example:

<code class="cpp">// Explicitly specify the type of the variable
auto dv: Timer = Timer();

// Explicitly declare the function's signature
int time_keeper(Timer (*)());</code>
Copy after login

The above is the detailed content of When Does C Uniform Initialization Become the \'Most Vexing Parse\'?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template