从构造函数的初始化程序列表中捕获异常 [英] Catching exceptions from a constructor's initializer list

查看:103
本文介绍了从构造函数的初始化程序列表中捕获异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这很奇怪。我有一个类A。它有一个类B,我想使用初始化列表在A的构造函数中对其进行初始化,例如:

Here's a curious one. I have a class A. It has an item of class B, which I want to initialize in the constructor of A using an initializer list, like so:

class A {
    public:
    A(const B& b): mB(b) { };

    private:
    B mB;
};

是否有一种方法可以捕获仍在使用初始化程序的mB的复制构造函数引发的异常列出方法?还是我必须在构造函数的括号内初始化mB才能进行尝试/捕获?

Is there a way to catch exceptions that might be thrown by mB's copy-constructor while still using the initializer list method? Or would I have to initialize mB within the constructor's braces in order to have a try/catch?

推荐答案

已阅读< a href = http://weseetips.wordpress.com/tag/exception-from-constructor-initializer-list/ rel = noreferrer> http://weseetips.wordpress.com/tag/exception-from-constructor -initializer-list / )

编辑:经过更多挖掘,这些被称为功能尝试块。

After more digging, these are called "Function try blocks".

我承认直到我继续寻找之前,我也不知道这一点。您每天都学到一些东西!我不知道这是否表明我如今很少使用C ++,我缺乏C ++知识或经常乱用该语言的拜占庭功能。嗯-我还是喜欢:)

I confess I didn't know this either until I went looking. You learn something every day! I don't know if this is an indictment of how little I get to use C++ these days, my lack of C++ knowledge, or the often Byzantine features that litter the language. Ah well - I still like it :)

为了确保人们不必跳到另一个站点,构造函数的try块的语法被证明是:

To ensure people don't have to jump to another site, the syntax of a function try block for constructors turns out to be:

C::C()
try : init1(), ..., initn()
{
  // Constructor
}
catch(...)
{
  // Handle exception
}

这篇关于从构造函数的初始化程序列表中捕获异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆