gpt4 book ai didi

c++ - 通过引用捕获的抛出对象的生命周期

转载 作者:太空狗 更新时间:2023-10-29 21:08:57 24 4
gpt4 key购买 nike

C++ 标准第 15.1.4 段说:

The memory for the temporary copy of the exception being thrown is allocated in an unspecified way, except as noted in 3.7.3.1. The temporary persists as long as there is a handler being executed for that exception.

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

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 block 之前被调用。但是,如果我向我的类添加一个复制构造函数:

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 block 的末尾)被调用,但有趣的是,复制构造函数仍然没有被调用。它是否被编译器优化掉了(关闭优化的 Visual C++ 2008),还是我遗漏了什么?

最佳答案

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

是的,正如您从标准中引用的那样,编译器会获取一份拷贝,而原始文件(可能)会被丢弃。您的问题是原始代码中缺少复制构造函数。但是,允许 C++ 编译器在各种情况下删除(或添加)复制构造函数调用,包括这种情况。

关于c++ - 通过引用捕获的抛出对象的生命周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2122739/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com