c++中的字符串构建异常是what()
String building in C++ exception’s what()
这个答案声明了一个private static ostringstream
。这个线程安全吗?如果两个线程同时抛出(并捕获,并记录what()
)异常,这工作可靠吗?如果我在本地声明ostringstream
,如:
virtual const char* what() const throw()
{
std::ostringstream cnvt.str( "" );
cnvt << runtime_error::what() << ": " << getNumerator()
<< " / " << getDenominator();
return cnvt.str().c_str();
}
是否有缺点(内存泄漏,或非法指针)?或者这是线程安全的方式吗?
No。它一点也不安全(而且对我来说效率很低,可以单独用std::string
来做)。为了安全起见,将ostringstream
声明为thread_local
static thread_local ostringstream cnvt;
还应该使cnvt
将字符串输出到某个成员字符串,以便不返回悬空指针。
class DivideByZeroException: public runtime_error {
public:
DivideByZeroException(int x, int y)
: runtime_error( "division by zero" ), numerator( x ), denominator( y )
{}
virtual const char* what() const throw()
{
cnvt.str( "" );
cnvt << runtime_error::what() << ": " << getNumerator()
<< " / " << getDenominator();
error = cnvt.str();
return error.c_str();
}
/*...*/
private:
std::string error;
int numerator;
int denominator;
static thread_local ostringstream cnvt;
};
还有,如果例外是"除以0",你不觉得存储分母有点傻吗?它总是0 !否则你不会抛出"除零"错误!
,最后由与数学误差有关的std::domain_error
推导出0除法误差更合适。
what()
是错误的地方建立字符串IMHO(尽管有不同的观点)。
std::runtime_error
已经包含了一个字符串,所以我们使用这个字符串。
#include <stdexcept>
#include <string>
struct DivideByZero : std::runtime_error
{
DivideByZero(int x, int y)
: std::runtime_error( make_message(x,y) )
{}
private:
static std::string make_message(int x, int y)
{
return std::string("division by zero: " + std::to_string(x) + '/' + std::to_string(y));
}
};
相关文章:
- 处理多个异常集合的C++方法
- 我在c++代码中生成了一个运行时#3异常
- 孤立代码块在结构中引发异常
- C++中的赋值发生,尽管右侧出现异常
- 多个文件的内存分配错误"在抛出 'std :: bad_alloc' what (): std :: bad_alloc 的实例后终止调用" [C++]
- 从构造函数抛出异常时如何克服内存泄漏
- 异常属于C++中的线程还是进程
- 当类定义不可见时捕获异常
- 引发异常:读取访问冲突**dynamicArray**为0x1118235.发生
- 为什么异常不退出程序?
- 为什么我应该在异常处理中使用std::cerr而不是std::cout
- 为什么重新抛出异常会丢弃"what()"给出的信息?
- 异常类 - what() 函数
- 如何在抛出未处理的自定义异常后调用 what()?
- 如何从c 中的异常类中定义what what what whate()函数
- 自定义异常并不总是执行 what()
- 来自 exception::what() 的异常描述是否针对标准异常进行了标准化
- 如何同时获取 what() 和回溯跟踪未捕获的异常
- c++中的字符串构建异常是what()
- 如何捕获一般异常并显示其派生的 what()