在std::exception中使用c_str()作为参数是否安全



在构造std::exception时,将c_str()作为参数传递是否安全?如果处理这样的异常是个坏主意,请告诉我。在我的项目中,所有错误消息都以std::string的形式从函数返回,然后以std::exception的形式抛出。

#include <iostream>
int main()
{
try {
std::string message="! Something went wrong.";
throw std::exception(message.c_str());
}
catch (std::exception ex) {
std::cerr << ex.what() << std::endl;
}
}

std::exception没有接受const char*std::string的构造函数。

std::runtime_error(及其子代(确实为这两者都有构造函数。是的,将message.c_str()指针传递给这个构造函数是非常安全的(好吧,前提是内存不低(。std::runtime_error会将字符数据复制到自己的内部内存中,从而允许在抛出异常后销毁message

如果你想用字符串消息抛出std::exception本身,你必须从中派生一个自定义类,并为what()实现自己的字符串缓冲区以返回指向的指针。在这种情况下,你必须小心不要从what()返回无效的const char*指针。std::runtime_error为您处理该问题,因此您应该从中派生。

最新更新