NetCDF-C++ 4.4.2 中 NcException 的Bug

现象:

try {
  ....  
} catch ( NcException &e ) {
   cout << e.what() << endl;
   return -1;
}


以上代码用于当有 NcException 异常时,打印异常内容,结束当前函数。

实际是打印出的信息是乱码而非预期的异常信息。

 

原因分析

以下是NcException::what 的源码

const char* NcException::what() const throw()
{
  std::ostringstream oss;
  oss << lineNumber;
  string message(exceptionName+": "+complaint+"\nfile: "+fileName+"  line:"+oss.str());
  return message.c_str();
}

返回的是局部变量 message 的 c_str()的结果。

当 what() 返回时,message 被析构了,返回的指针也随之失效。

 

解决方案:

在NcException 中定义私有成员 message, 见代码第8行

 

class NcException : public std::exception {
public:
  NcException(const std::string& exceptionName,const std::string& complaint,const char* fileName,int lineNumber);
  virtual ~NcException() throw();
  const char* what() const throw();
private:
  std::string exceptionName, complaint, fileName;
  std::string message;
  int lineNumber;
};


然后修改 NcException::What(), 取消局部变量 message, 使用成员变量 message。 只是由于 what() 是 const 函数,所以对 成员变量 message 的修改需要使用 const_cast.

const char* NcException::what() const throw()
{
  std::ostringstream oss;
  oss << lineNumber;
  const_cast< NcException * >( this )->message
	  = (exceptionName+": "+complaint+"\nfile: "+fileName+"  line:"+oss.str());
  return message.c_str();
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值