“ void()”如何有用?

gez*_*eza 1 c++ void variable-declaration

您不能声明void变量:

void fn() {
    void a; // ill-formed
}
Run Code Online (Sandbox Code Playgroud)

但这编译为:

void fn() {
    void(); // a void object?
}
Run Code Online (Sandbox Code Playgroud)

什么void()意思 有什么用?为什么void a;格式不正确,但void()可以?

void fn() {
    void a = void(); // ill-formed
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ica 5

The statement

void();
Run Code Online (Sandbox Code Playgroud)

creates a void value and then discards it. (You can't actually do much with a void value other than discard it or return it.)

The standard† says in 5.2.3 [expr.type.conv

The expression T(), where T is a simple-type-specifier or typename-specifier for a non-array complete object type or the (possibly cv-qualified) void type, creates a prvalue of the specified type, whose value is that produced by value-initializing (8.5) an object of type T; no initialization is done for the void() case

Note that it explictaly calls out that void() is legal.

† My link is to N4296 which was the last public committee draft before C++14, however the various versions of the standard do not vary here.


Edit

Is it useful? Explicitly like this? No. I can't see a use for it. It is however, useful in template functions which sometimes do something like:

template <typename T>
T foo() {
    if (prepare_for_for()) {
        return do_foo();
    } else {
        return T();
    }
}
Run Code Online (Sandbox Code Playgroud)

And this will work, even for T == void.