• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

kaikai向前走

转职任务完成。崭新fn诞生
  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

[导入]对编写安全的代码这个方法有用吗?

我又突发奇想了。
如果可以方便的添加一下try catch在你的代码里。能用来做什么呢?
Code:

#include
#include

#ifdef USE_SAFE
#   define SAFE_FUNCTION(foo,b) foo \
{  \
   try{ \
       b \
    } \
   catch(...) \
   {   \
       assert(0 && #foo ); \
    } \
}
#else
#   define SAFE_FUNCTION(foo,b) foo \
{  \
 b\
}
#endif

SAFE_FUNCTION( int foo(int a,int b) ,

 assert(b!=0 && "hi");
 printf("%d\n",a/b);    
 return 0;

)

int main()
{
   foo(1,1);
   foo(1,0);
   return 0;
}

定义了SAFE_FUNCTION这个宏之后,每次定义一个函数都使用这个宏,那么这些函数都被自动的加上了一个try catch对。可惜对于调试工具来说,错误定位却困难了...
没试过其他的,vc只能跟踪到使用SAFE_FUNCTION定义函数的末尾一行。而且一步就跨越过去了。
目前还没有想到有什么用处。也许同一模块的函数具有相同的出错处理的话,可以使用这个宏。修改catch段的处理方式,甚至再用一个宏
Code:

#ifdef USE_SAFE
#   define SAFE_FUNCTION(foo,b,error) foo \
{  \
   try{ \
       b \
    } \
   catch(...) \
   {   \
       error \
    } \
}
#else
#   define SAFE_FUNCTION(foo,b,error) foo \
{  \
 b\
}
#endif


#define DEF_SAFE_FUNCTION(foo,b) SAFE_FUNCTION(foo, b, assert(0 && #foo))

#define ANOTHER_SAFE_FUNCTION(foo,b) SAFE_FUNCTION(foo, b,  \
printf("Error in %s\n", #foo);  \
)


这样,在不同模块的处理可以是不同的。

( 网页浏览 )
文章来源:http://acm.tongji.edu.cn/people/kaikai/blog/blog.php?job=art&articleid=a_20041125_142918

posted on 2004-12-15 17:49  kaikai  阅读(486)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3