现在的位置: 首页 > 综合 > 正文

new和delete操作符重载

2013年10月15日 ⁄ 综合 ⁄ 共 1378字 ⁄ 字号 评论关闭
  1. #include <iostream>
  2. #include <new>
  3. using namespace std;
  4. class MemoryPool
  5. {
  6. };
  7. class MemoryObject
  8. {
  9. private:
  10.     MemoryPool* aPool;
  11. public:
  12.     MemoryObject(MemoryPool* p)
  13.     {
  14.         aPool = p;
  15.     };  
  16.     voidoperator new(size_t);
  17.     static voidoperator new(size_t, int i);
  18. };
  19. void* MemoryObject::operator new(size_t)
  20. {
  21.     return NULL;
  22. }
  23. void* MemoryObject::operator new(size_t,int i)
  24. {
  25.     return NULL;
  26. }
  27. void main()
  28. {
  29.     MemoryPool aPool;
  30.     void* p = new MemoryObject(&aPool);
  31.     if (p==NULL)
  32.     {
  33.         cout<<"NULL p"<<endl;
  34.     }
  35.     void* p2 = new(3) MemoryObject(&aPool);
  36.     if (p2==NULL)
  37.     {
  38.         cout<<"NULL p2"<<endl;
  39.     }
  40. };

在编写内存池代码的时候,遇到这个问题,遂解决之。

参考:http://kuapig.ycool.com/post.2726735.html

下面是一个稍微复杂一点的例子:注意,重载了new以后,没有执行构造函数。

  1. #include <iostream>
  2. #include <new>
  3. using namespace std;
  4. class MemoryPool;
  5. class MemoryObject
  6. {
  7. public:
  8.     const MemoryPool* aMemPool;
  9. public:
  10.     MemoryObject(const MemoryPool* obj):aMemPool(obj)
  11.     {
  12.     }
  13.     static voidoperator new(size_t,int a,int b)
  14.     {
  15.         return NULL;
  16.     }
  17. };
  18. class MemoryPool
  19. {
  20. public:
  21.     int i;
  22.     MemoryPool():i(98){};
  23. };
  24. void main()
  25. {
  26.     MemoryPool aMemPool;
  27.     MemoryObject aMemObj(&aMemPool);
  28.     cout<<(aMemObj.aMemPool)->i<<endl;
  29.     void * p = new(3,5) MemoryObject(&aMemPool);
  30.     if (p==NULL)
  31.     {
  32.         cout<<"asdsadsa"<<endl;
  33.     }
  34. }

明白了new重载的道理,我们在new MemoryObject对象的时候,就知道如何将底层的实现送给MemoryPool的Alloc函数处理了,最后的返回值,实际上是MemoryPool处理后返回的。

 

抱歉!评论已关闭.