c++ - 不能在带有 try/catch 的构造函数初始化列表中使用统一初始化

标签 c++ gcc c++11 g++ uniform-initialization

following code不使用 gcc 编译:

struct test {
    int x;
    test() try : x{123} {
    }
    catch (...) {
    }
};

int main() {}

错误:

prog.cpp:3:25: error: expected unqualified-id before ‘{’ token
     test() try : x{123} {
                         ^
prog.cpp:5:5: error: expected unqualified-id before ‘catch’
     catch (...) {
     ^
prog.cpp: In constructor ‘test::test()’:
prog.cpp:3:23: error: expected ‘{’ at end of input
     test() try : x{123} {
                       ^
prog.cpp:3:23: error: expected ‘catch’ at end of input
prog.cpp:3:23: error: expected ‘(’ at end of input
prog.cpp:3:23: error: expected type-specifier at end of input
prog.cpp:3:23: error: expected ‘)’ at end of input
prog.cpp:3:23: error: expected ‘{’ at end of input

x{123} 更改为 x(123) 会有所帮助。这应该(不)以这种方式工作吗?

最佳答案

根据标准的语法这是有效的(大括号见 [gram.special],try-catch 见 [gram.except]。GCC 4.8 有错误,但 GCC 4.9 正确处理了它(正如其他编译器一样,如前所述)。

我不知道为什么 BS 在他的书中不使用这种语法。也许是因为当他编译他的示例以查看它们是否正确(如果他这样做了)时,他手头没有任何支持这种语法的编译器?

关于c++ - 不能在带有 try/catch 的构造函数初始化列表中使用统一初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18675881/

相关文章:

c++ - 如何在 boost (c++) 中将内存页锁定到物理 RAM?

c++ - 适用于8位MCU的更快的16位乘法算法

c++ - 如何禁止复制构造函数并仅使用移动构造函数?

c++ - 如何在 OpenCV 中设置 ROI?

c++ - Qt5链接错误

c++ - 在进行基准测试时防止编译器优化

c - 为什么链接程序需要 stdlib?

c++ - 措辞: Is there a difference b/w rvalue and rvalue references?

c++ - 是一个二叉树 BST 但只有右 child 才允许重复

用户定义的c++常量变量