当 return 语句、逗号运算符、花括号初始化列表和 std::unique_ptr 组合在一起时

4Le*_*Cat 4 c++

在下面的代码中,为什么我会收到编译错误,而n = 8所有其他情况都正常?我的目的是报告一些错误并返回空指针,而不用不必要的大括号使代码混乱。我将使用 nullptr 来达到此目的,但我很好奇为什么{}无法使用逗号运算符进行编译,而它单独工作。

您可以在此处使用此代码。我使用C++20设置。

#include <cstdint>
#include <memory>

void oops(const char*) {
}

std::unique_ptr<uint8_t[]> please_do(int n) {
    if (n == 1)
        return std::unique_ptr<uint8_t[]>(); // compiles ok
    if (n == 2)
        return oops(""), std::unique_ptr<uint8_t[]>(); // compiles ok

    if (n == 3)
        return std::make_unique<uint8_t[]>(n); // compiles ok
    if (n == 4)
        return oops(""), std::make_unique<uint8_t[]>(n); // compiles ok

    if (n == 5)
        return nullptr; // compiles ok
    if (n == 6)
        return oops(""), nullptr; // compiles ok

    if (n == 7)
        return {}; // compiles ok
    if (n == 8)
        return oops(""), {}; // why compilation error?

    return nullptr; // compiles ok
}

int main() {
    please_do(42);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

GCC 9.2 输出:

<source>: In function 'std::unique_ptr<unsigned char []> please_do(int)':

<source>:26:26: error: expected primary-expression before '{' token

   26 |         return oops(""), {}; // why compilation error?

      |                          ^

<source>:26:25: error: expected ';' before '{' token

   26 |         return oops(""), {}; // why compilation error?

      |                         ^~

      |                         ;
Run Code Online (Sandbox Code Playgroud)

Clang 9.0.0 输出:

<source>:26:16: error: no viable conversion from returned value of type 'void' to function return type 'std::unique_ptr<uint8_t []>'

        return oops(""), {}; // why compilation error?

               ^~~~~~~~

/opt/compiler-explorer/gcc-9.2.0/lib/gcc/x86_64-linux-gnu/9.2.0/../../../../include/c++/9.2.0/bits/unique_ptr.h:528:7: note: candidate constructor not viable: cannot convert argument of incomplete type 'void' to 'std::unique_ptr<unsigned char [], std::default_delete<unsigned char []> > &&' for 1st argument

      unique_ptr(unique_ptr&& __u) noexcept

      ^

/opt/compiler-explorer/gcc-9.2.0/lib/gcc/x86_64-linux-gnu/9.2.0/../../../../include/c++/9.2.0/bits/unique_ptr.h:533:12: note: candidate constructor template not viable: cannot convert argument of incomplete type 'void' to 'std::nullptr_t' (aka 'nullptr_t') for 1st argument

        constexpr unique_ptr(nullptr_t) noexcept

                  ^

/opt/compiler-explorer/gcc-9.2.0/lib/gcc/x86_64-linux-gnu/9.2.0/../../../../include/c++/9.2.0/bits/unique_ptr.h:681:7: note: candidate constructor not viable: cannot convert argument of incomplete type 'void' to 'const std::unique_ptr<unsigned char [], std::default_delete<unsigned char []> > &' for 1st argument

      unique_ptr(const unique_ptr&) = delete;

      ^

/opt/compiler-explorer/gcc-9.2.0/lib/gcc/x86_64-linux-gnu/9.2.0/../../../../include/c++/9.2.0/bits/unique_ptr.h:542:2: note: candidate template ignored: could not match 'unique_ptr<type-parameter-0-0, type-parameter-0-1>' against 'void'

        unique_ptr(unique_ptr<_Up, _Ep>&& __u) noexcept

        ^

<source>:26:24: error: expected expression

        return oops(""), {}; // why compilation error?

                       ^
Run Code Online (Sandbox Code Playgroud)

HTN*_*TNW 5

{}不是一个表达式。是它自己的特殊语法(列表初始化return {...};的一种形式),它从函数的签名中计算出返回类型,就好像 by where是返回类型一样:Ret{...}Ret

Ret f() {
    return {...}; // special syntax for return; {args...} need not be a valid expression
}
// same as
Ret f() {
    return Ret{...}; // generic return <expression> syntax; Ret{args...} must be a valid expression
}
Run Code Online (Sandbox Code Playgroud)

中没有特殊的语法return a, ba, b它只是使用正常语法返回的表达式return。逗号运算符要求 和a都是b表达式,但由于{}不是表达式,因此像这样的表达式oops(""), {}无效语法。

顺便说一句,还有其他地方{...}可以使用它,使其看起来像是一个表达式,但实际上不是,例如函数调用:

void f(std::string);
f({5, 'a'})
Run Code Online (Sandbox Code Playgroud)

同样,虽然这看起来像是{5, 'a'}一个带有类型的表达式std::string(正如其意图),但事实并非如此。它{5, 'a'}是函数调用本身的一部分,其类型由重载决策决定。

至于编译器错误,它们都因oops(""), {}表达式语法无效这一事实而感到困惑。GCC 似乎已读取oops(""),,因此期望随后出现一个表达式。但表达式不能以 开头{,因此它读取该字符并立即呕吐,抱怨它正在等待表达式开始。Clang 也做同样的事情。我认为 Clang 然后继续,为了寻求“帮助”,假装您只是没有编写该, {};部分(也就是说,就好像您编写了一样return oops("");),并为此发出错误。例如,这种行为允许 Clang 提供有用的类型错误,即使您拼写错误;也就是说,如果你要运行 Clang

void supercalifragilisticexpialidocious(std::string);
int main() { supercalifragilisticexpialidociuos(7); }
Run Code Online (Sandbox Code Playgroud)

它首先会针对错误的拼写 ( ) 发出错误,建议正确的拼写,然后针对和参数类型-ous -> -uos之间的类型不匹配发出错误,就好像您已经修复了拼写一样。同样,在这里,它会因错误语法发出一个错误,然后发出第二个错误,就好像您已经摆脱了错误语法一样。但是,在这种情况下它并不是很有帮助,因为它想象您使用的“修复”并不是实际的修复。int 7std::string