文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>C++ exception error messages 选项

C++ exception error messages 选项

时间:2010-09-25  来源:蓝天寂寞

今天,在tom的伯克利看到这么一篇博文,很有感触。转摘如下:   An awkward situation with exception handling occurred to me this morning.

I frequently see (and I'll admit to writing it myself sometimes) error
detection code which does something along these lines:

  if(badness) {
     std::ostringstream err;
     err << "Badness " << errcode << " has occurred while frobbing"
         << " nitzes.  blah blah blah";
     throw SomeException(err.str().c_str());
  }

or just using snprintf:

  if(badness) {
     char errc[1024];
     snprintf(errc, 1024, "badness %d occurred ...", errcode);
     throw SomeException(errc);
  }

Yet, of course, by the time we get to a:

  catch(const SomeException& se) { ... }

clause somewhere up the call stack, the above stack has unwound.  In the
first case, the std::string from err.str() has had its destructor run,
so our saved pointer is bogus; in the latter, there's no destructor for
char* of course but the 'errc' array is "gone".

Consider:

  void X() {
     try {
       Y();
     } catch(const SomeException& se) {
       std::cerr << se.what() << "\n";
     }
  }

  void Y() {
    Z();
  }

  void Z() {
    if(badness) { ... /* as above */ }
  }

'se' stores a pointer to, say 'errc' (second case).  This is probably
fine, because 'errc' is technically still around.  Still, I no longer
"own" 'errc'.  If things were changed and the stack for 'Y' or 'Z' was
gigantic for some reason, the operating system might presumably sbrk()
or something to shrink the stack size and reclaim the memory (granted, I
don't think this would happen w/ any OS/C++ runtime I use, but I'm
asking if this would be legal), no?  In that case, accessing the pointer
stored in 'errc' would lead to a segmentation fault.

What have I misinterpreted?

Thanks,

-tom

相关阅读 更多 +
排行榜 更多 +
鸡生化精英安卓版

鸡生化精英安卓版

飞行射击 下载
光头火柴人安卓版

光头火柴人安卓版

飞行射击 下载
轨道射击安卓版

轨道射击安卓版

飞行射击 下载