Chinaunix首页 | 论坛 | 博客
  • 博客访问: 300160
  • 博文数量: 35
  • 博客积分: 836
  • 博客等级: 准尉
  • 技术积分: 678
  • 用 户 组: 普通用户
  • 注册时间: 2011-11-07 20:11
文章分类

全部博文(35)

文章存档

2013年(1)

2012年(24)

2011年(10)

分类: C/C++

2012-03-14 13:43:40

昨天用placement new初始化从内存池申请的一块内存。晚上回家路上突然想到,从内存池申请下来忘了检查是否成功了,直接就new(ptr)了。以为这样会出core。不过转念一想new怎么也会检查下指针是不是为NULL吧。所以今天早上写了一段代码做了个实验,实验证明,placement new是会判断ptr是否为NULL的。如果是NULL,直接返回。

代码如下:
  1. #include <new>
  2. #include <iostream>
  3. class boo_t
  4. {
  5. public:
  6.     boo_t():
  7.         _a(0),
  8.         _b(0)
  9.     {
  10.     }
  11. private:
  12.     int _a;
  13.     int _b;
  14. };
  15. int main(int argc, char *argv[])
  16. {
  17.     void *buf = (void *)0;
  18.     boo_t *a = new(buf) boo_t();

  19.     std::cout<< "OK, get here and a is " << a << std::endl;

  20.     return 0;
  21. }
如果placement new不做检测的话,那么就会出core,结果程序正常运行,输出结果:
  1. OK, get here and a is 0
如果将代码改为如下:
  1. #include <new>
  2. #include <iostream>
  3. class boo_t
  4. {
  5. public:
  6.     boo_t():
  7.         _a(0),
  8.         _b(0)
  9.     {
  10.     }
  11. private:
  12.     int _a;
  13.     int _b;
  14. };
  15. int main(int argc, char *argv[])
  16. {
  17.     void *buf = (void *)1;
  18.     boo_t *a = new(buf) boo_t();

  19.     std::cout<< "OK, get here and a is " << a << std::endl;

  20.     return 0;
  21. }
只是将buf换为了1,但是同样是非法内存,这个破坏了NULL的检测,所以结果就是core dump。

通过以上就是想说,placement new简单的NULL检测还是有的,所以内存申请失败不要紧,放心大胆的用吧。new之后再检测也不晚。

阅读(2880) | 评论(0) | 转发(0) |
0

上一篇:Timer的设计

下一篇:Linux timer VS 红黑树Timer

给主人留下些什么吧!~~