通过引用捕获的抛出对象的生存期 [英] Lifetime of a thrown object caught by reference

查看:128
本文介绍了通过引用捕获的抛出对象的生存期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++标准,第15.1.4节:sais:

The C++ Standard, paragraph 15.1.4 sais:


正在抛出的异常的临时副本的内存分配在未指定的方式,除了3.7.3.1中所述。 暂停只要存在为该异常执行的处理程序,就会暂停。

为什么这个代码崩溃(我知道这不是最佳实践):

I'm wondering why this code crashes (I know that it's not best practice):

class magicException
{
private:
    char* m_message;

public:
    magicException(const char* message)
    {
        m_message = new char[strlen(message) + 1];
        strcpy(m_message, message);
    }

    ~magicException()
    {
        cout << "Destructor called." << endl;
        delete[] m_message;
    }

    char* getMessage()
    {
        return m_message;
    }
};

void someFunction()
{
    throw magicException("Bang!");
}

int main(int argc, char * argv[])
{
    try
    {
        someFunction();
    }
    catch (magicException& ex)
    {
        cout << ex.getMessage() << endl;
    }

    return 0;
}

具体来说,抛出的magicException对象的析构函数在catch块之前被调用。如果我添加一个复制构造函数到我的类:

Specifically, the destructor of the thrown magicException object gets called before the catch block. If I however add a copy constructor to my class:

magicException(const magicException& other)
{
    cout << "Copy constructor called." << endl;
    m_message = new char[strlen(other.m_message) + 1];
    strcpy(m_message, other.m_message);
}

然后代码工作,析构函数在预期的地方的catch块),但有趣的是,复制构造函数仍然不被调用。它是由编译器优化的(Visual C ++ 2008的优化关闭),或者我缺少一些东西?

Then the code works, the destructor gets called at the expected place (the end of the catch block), but interestingly the copy constructor still doesn't get called. Is it optimized away by the compiler (Visual C++ 2008 with optimizations turned off), or am I missing something?

推荐答案

$ b

具体来说,
抛出的magicException对象的析构函数在catch块之前调用

Specifically, the destructor of the thrown magicException object gets called before the catch block.

是的,从标准的报价说,复制由编译器采取,并且原始(可能)丢弃。你的问题是你的原始代码中缺少一个复制构造函数。但是,允许C ++编译器在各种情况下删除(或添加)复制构造函数调用,包括这一个。

Yes, as your quote from the standard says, a copy is taken by the compiler, and the original (probably) discarded. Your problem is the lack of a copy constructor in your original code. However, a C++ compiler is allowed to remove (or add) copy constructor calls in all sorts of situations, including this one.

这篇关于通过引用捕获的抛出对象的生存期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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