【问题标题】:Try-Catch std::bad_alloc outside function?Try-Catch std::bad_alloc 外部函数?
【发布时间】:2021-11-02 07:34:27
【问题描述】:

我有:

class image {
public:
    linked_list<int, int> UnLabeledList;

    explicit image(int Segments) {//some code}
};

链表的C'tor在哪里:

linked_list() {
    total_nodes = 0;
    first = new node<S, T>{}; //Dummy
    first->height = NOT_INIT;
    last = first;
}

如何检测这条线路是否失败? linked_list&lt;int, int&gt; UnLabeledList;

它在任何函数之外,所以我不能尝试并捕捉......

【问题讨论】:

标签: c++ class try-catch new-operator allocation


【解决方案1】:

在本例中,您根本不需要在image 构造函数中检测异常。该异常将取消UnLabeledList 成员的构造,该成员在image 构造函数的成员初始化期间运行,然后进入image 构造函数的主体。在抛出异常之前成功创建的任何其他image 成员将被自动销毁。

异常将被抛出到构造image 对象的代码中。如果需要,您可以在该代码中使用 try/catch

如果您绝对需要在 image 的构造函数中捕获异常(这在正确编写的代码中非常罕见),您可以在构造函数的 member initialization list 周围使用 function-try,例如:

class image {
public:
    linked_list<int, int> UnLabeledList;

    explicit image(int Segments) try : UnLabeledList() {
        // some normal code...
    } catch (...) {
        // some error handling code...
    } // <-- exception is automatically rethrown here!
};

【讨论】:

    猜你喜欢
    • 2012-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多