【发布时间】:2013-05-21 19:16:46
【问题描述】:
以下代码是否安全地抛出带有自定义消息的异常?
#include <exception>
#include <sstream>
#include <string>
#include <iostream>
int main() {
try {
std::ostringstream msg;
msg << "give me " << 5;
throw std::exception(msg.str().c_str());
} catch (std::exception& e) {
std::cout << "exception: " << e.what();
}
}
使用 VC++-2008 这给出了:
exception: give me 5
但是现在我想知道为什么来自本地对象msg 的消息“给我5”仍然在catch 块中可用?在打印消息时,流对象和临时字符串对象都应该被删除吗?顺便说一句:这种为异常生成消息的方式似乎也适用于多个函数,并且如果在打印异常之前在 catch 块中分配了新内存。
或者是否有必要使用 std::string 成员定义自定义异常类,以便在打印之前安全地保留消息。
【问题讨论】:
标签: c++ visual-c++ exception