【问题标题】:can't use uniform initialization in constructor initialization list with try/catch不能在带有 try/catch 的构造函数初始化列表中使用统一初始化
【发布时间】:2013-09-07 17:16:39
【问题描述】:

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) 会有所帮助。这应该(不)以这种方式工作吗?

【问题讨论】:

  • Clang compiles it 没有错误
  • 任何与大括号和 C++11 相关的事情很可能在一段时间内在编译器中没有完全实现极端情况......
  • @KerrekSB 我最初认为这是一个错误,但在 Stroustrup 的书中,他在构造函数中使用统一初始化,除非有 try/catch,所以这让我有点困惑。
  • Intel C++ 13.1.3 编译它也没有错误。
  • gcc 主线编译它。

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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-19
    • 1970-01-01
    • 2012-05-17
    相关资源
    最近更新 更多