为什么是catch(bad_alloc &e),而不是catch(const bad_alloc &e) ?

yaoyansi 2012-02-14 03:46:54
Hi,
关于异常,有个问题请教一下:
More EffectiveC++里M14里推荐使用引用来捕获异常:
try{
...
}catch(bad_alloc &e){
...
}
为什么不是const bad_alloc &e呢?即:
try{
...
}catch(const bad_alloc &e){
...
}
在catch块里,还需要改变e吗?

谢谢
...全文
310 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
程序员小迷 2012-02-15
  • 打赏
  • 举报
回复
楼主测试一下这个代码,就晓得了:



class A
{
public:
A(int i = 0):i(i) { }

public:
void setI(int newI)
{
i = newI;
}

private:
int i;
};

int main()
{
const A a(1);
a.setI(2); // 编译错误
return 0;
}

northcan 2012-02-14
  • 打赏
  • 举报
回复
try{
...
}catch(const bad_alloc &e){
...
}
这样也可以吧。

不过对于有些Exception类,比如:
class CppSQLite3Exception
{
public:
CppSQLite3Exception(const int nErrCode, LPTSTR szErrMess, bool bDeleteMsg=true);
CppSQLite3Exception(const CppSQLite3Exception& e);
virtual ~CppSQLite3Exception();

const int errorCode() { return mnErrCode; }
LPCTSTR errorMessage() { return mpszErrMess; }
static LPCTSTR errorCodeAsString(int nErrCode);

private:
int mnErrCode;
LPTSTR mpszErrMess;
};

这时候如果下面这样,就会出现语法错误,编译不过。
try{
...
}
catch(const CppSQLite3Exception &ex){
AfxMessageBox(ex.errorMessage());
ret = ex.errorCode();
}

vs2008会提示:
error C2662: 'CppSQLite3Exception::errorMessage' : cannot convert 'this' pointer from 'const CppSQLite3Exception' to 'CppSQLite3Exception &'

error C2662: 'CppSQLite3Exception::errorCode' : cannot convert 'this' pointer from 'const CppSQLite3Exception' to 'CppSQLite3Exception &'
luciferisnotsatan 2012-02-14
  • 打赏
  • 举报
回复
是否要改变e,看实际需求。

至于书里,作者那时关注的应该是用引用。没去考虑const这个问题。
  • 打赏
  • 举报
回复
都可以啊。
pengzhixi 2012-02-14
  • 打赏
  • 举报
回复
那就看bad_alloc里面有没有const成员函数。尤其是what成员函数,如果没有那么用这个的话就没办法调用这些成员函数了

64,649

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧