【问题标题】:Throwing an exception from a constructor - Core Dumped从构造函数中抛出异常 - 核心转储
【发布时间】:2016-01-07 19:41:24
【问题描述】:

这是我执行的代码:

B::B(Ptr* myPtr)
    : A( myPtr!=nullptr ? myPtr->someFunction()
                        : throw std::invalid_argument("Invalid_argument") )
    , localPtr_(myPtr)
{}

所以,我的类是以指针作为参数构造的。如果这个指针是 nullptr 我想抛出一个 Invalid Argument 异常。

我主要有:

A* myAobject = new B(nullptr);

所以,我期望编译器抛出异常,然后调用所创建对象的析构函数。

但我明白了:

terminate called after throwing an instance of 'std::invalid_argument'
  what():  Invalid_argument
Aborted (core dumped)

如果我尝试:gdb ./main core.main 我明白了:

Program terminated with signal SIGABRT, Aborted.
#0  0x00007fe14f81bcc9 in __GI_raise (sig=sig@entry=6) at     ../nptl/sysdeps/unix/sysv/linux/raise.c:56
56  ../nptl/sysdeps/unix/sysv/linux/raise.c: No such file or   directory.
Traceback (most recent call last):
  File "/usr/share/gdb/auto-load/usr/lib/x86_64-linux-    gnu/libstdc++.so.6.0.19-gdb.py", line 63, in <module>
    from libstdcxx.v6.printers import register_libstdcxx_printers
ImportError: No module named 'libstdcxx'

我不明白为什么...你能帮帮我吗?

【问题讨论】:

    标签: c++ core


    【解决方案1】:

    你需要捕捉异常:

    try
    {
        A* myAobject = new B(nullptr);
    }
    catch (std::invalid_argument& e)
    {
        // do something, exception was thrown...
    }
    

    注意 A 在这种情况下不会调用析构函数,因为对象实际上从未完全创建。在这里测试:http://cpp.sh/7fmr

    调用析构函数是不安全的,看这个例子:

    class B
    {
    public:
        B( bool param ) : m_b1( (param) ? new int() : throw std::runtime_error("")
        {
            m_b2 = new int();
        }
        ~B()
        {
            delete m_b1;
            delete m_b2;
        }
    };
    

    如果在构造函数抛出异常时调用析构函数,m_b2 保持未初始化,从析构函数中删除它会出现段错误。

    【讨论】:

    • 我确定创建的对象被破坏了吗?显然,没有调用析构函数...
    • @aky - 由于异常,对象从未完全构造。所以没有要破坏的对象。
    猜你喜欢
    • 2011-11-04
    • 2019-03-11
    • 2023-03-11
    • 1970-01-01
    • 2010-10-29
    • 1970-01-01
    • 2014-11-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多