Catch block in constructor without try

杀马特。学长 韩版系。学妹 提交于 2019-12-24 02:52:03

问题


I have the following code:

#include <iostream>
using namespace std;

int foo()
{
    throw 1;
}

struct A {
    int a;
    public:
    A() try : a(foo())
    {
        cout << "Constructor A\n";
    } catch(...)
    {
        cout << "Catched in A\n";
    }
};

struct B : A {
    B()
    {
        cout << "Constructor B\n";
        ::foo();
    } catch(...)
    {
        cout << "Catched in B\n";
    }
    void foo()
    {

    }
    catch(...)
    {
        cout << "Catched in foo\n";
    }
};

int main () try
{
    B b;
    return 0;
} catch (...)
{
    cout << "Catched in main\n";
}

It outputs:

Catched in A

Catched in main

Why B's catch block doesn't catch anything? And how can it exist withouth try?

Clang only detects error on line 26: error: expected member name or ';' after declaration specifiers and thinks that B::foo's block is OK. I'm confused :)

Clang++ v 3.4

gcc v 4.8

来源:https://stackoverflow.com/questions/38414951/catch-block-in-constructor-without-try

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!