- #include <iostream>
- #include <new>
- using namespace std;
- class MemoryPool
- {
- };
- class MemoryObject
- {
- private:
- MemoryPool* aPool;
- public:
- MemoryObject(MemoryPool* p)
- {
- aPool = p;
- };
- void* operator new(size_t);
- static void* operator new(size_t, int i);
- };
- void* MemoryObject::operator new(size_t)
- {
- return NULL;
- }
- void* MemoryObject::operator new(size_t,int i)
- {
- return NULL;
- }
- void main()
- {
- MemoryPool aPool;
- void* p = new MemoryObject(&aPool);
- if (p==NULL)
- {
- cout<<"NULL p"<<endl;
- }
- void* p2 = new(3) MemoryObject(&aPool);
- if (p2==NULL)
- {
- cout<<"NULL p2"<<endl;
- }
- };
在编写内存池代码的时候,遇到这个问题,遂解决之。
参考:http://kuapig.ycool.com/post.2726735.html
下面是一个稍微复杂一点的例子:注意,重载了new以后,没有执行构造函数。
- #include <iostream>
- #include <new>
- using namespace std;
- class MemoryPool;
- class MemoryObject
- {
- public:
- const MemoryPool* aMemPool;
- public:
- MemoryObject(const MemoryPool* obj):aMemPool(obj)
- {
- }
- static void* operator new(size_t,int a,int b)
- {
- return NULL;
- }
- };
- class MemoryPool
- {
- public:
- int i;
- MemoryPool():i(98){};
- };
- void main()
- {
- MemoryPool aMemPool;
- MemoryObject aMemObj(&aMemPool);
- cout<<(aMemObj.aMemPool)->i<<endl;
- void * p = new(3,5) MemoryObject(&aMemPool);
- if (p==NULL)
- {
- cout<<"asdsadsa"<<endl;
- }
- }
明白了new重载的道理,我们在new MemoryObject对象的时候,就知道如何将底层的实现送给MemoryPool的Alloc函数处理了,最后的返回值,实际上是MemoryPool处理后返回的。