- #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處理後返回的。