简体   繁体   中英

can't use uniform initialization in constructor initialization list with try/catch

The following code does not compile with gcc:

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

int main() {}

Errors:

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

Changing x{123} to x(123) helps. Is this supposed to (not) work this way?

This is valid according to the grammar of the standard (see [gram.special] for the braces, and [gram.except] for try - catch . GCC 4.8 has it wrong, but GCC 4.9 handles it properly (as do other compilers, as already reported).

I have no idea why BS does not use this syntax in his book. Maybe because he didn't have any compiler at hand that supported this syntax when he compiled his examples to see if they are right (if he did)?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM