Home  >  Article  >  Backend Development  >  When Does C Uniform Initialization Become the \"Most Vexing Parse\"?

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

DDD
DDDOriginal
2024-11-01 21:37:29975browse

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>

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>

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!

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