What is the meaning of this syntax?

2020-08-26 03:13发布

问题:

I have seen the peculiar syntax in an SO question a while ago.

class B{
    A a;
    public:
        B() try : a() {} catch(string& s) { cout << &s << " " << s << endl; };
};

What is the meaning of this try-catch-block outside the function?

回答1:

It's function try block. Usefull only in c-tors for catch errors in derived classes constructors. You can read more about this feature in standard for example n3337 draft par. 15, 15.1.

4 A function-try-block associates a handler-seq with the ctor-initializer, if present, and the compound-statement. An exception thrown during the execution of the compound-statement or, for constructors and destructors, during the initialization or destruction, respectively, of the class’s subobjects, transfers control to a handler in a function-try-block in the same way as an exception thrown during the execution of a try-block transfers control to other handlers. [ Example:

int f(int);
class C {
int i;
double d;
public:
C(int, double);
};
C::C(int ii, double id)
try : i(f(ii)), d(id) {
// constructor statements
}
catch (...) {
// handles exceptions thrown from the ctor-initializer
// and from the constructor statements
}

—end example ]



回答2:

It catches exceptions thrown from a constructor when creating a member object. One of the answers to the question you mentioned contains a link explaining the details: http://www.gotw.ca/gotw/066.htm.



标签: c++ syntax