2012-03-31 33 views
2

我有一個關於提供自定義刪除方法boost::shared_ptr構造函數的問題。自定義刪除提升shared_ptr

例如,我有一個GameObjectFactory類創建/銷燬GameObjects。它有一個MemoryManager的實例,它可以是Allocate()/Deallocate()的內存。 CreateObject()返回GameObject,通過MemoryManager分配,封裝在boost::shared_ptr中。

boost::shared_ptr破壞時,它應該調用我的MemoryManager->Deallocate()方法。然而,我不能正確的解決問題。我得到這些錯誤:

error C2276: '&' : illegal operation on bound member function expression 
error C2661: 'boost::shared_ptr<T>::shared_ptr' : no overloaded function takes 2 arguments 

我已閱讀提升文檔和我從計算器得到了命中率,但我無法得到它的權利。我不明白爲什麼下面的dosnt工作。

這是我的代碼;

#ifndef _I_GAMEOBJECT_MANAGER_H 
#define _I_GAMEOBJECT_MANAGER_H 

#include "../../Thirdparty/boost_1_49_0/boost/smart_ptr/shared_ptr.hpp" 

#include "EngineDefs.h" 
#include "IMemoryManager.h" 
#include "../Include/Core/GameObject/GameObject.h" 

namespace Engine 
{ 
    class IGameObjectFactory 
    { 
    public: 
     virtual ~IGameObjectFactory() { } 

     virtual int32_t Init() = 0; 
     virtual bool Destroy() = 0; 
     virtual bool Start() = 0; 
     virtual bool Stop() = 0; 
     virtual bool isRunning() = 0; 
     virtual void Tick() = 0; 

     template <class T> 
     inline boost::shared_ptr<T> CreateObject() 
     { 
      boost::shared_ptr<T> ptr((T*) mMemoryMgr->Allocate(sizeof(T)),&mMemoryMgr->Deallocate); 


      return ptr; 
     } 

     template <class T> 
     inline boost::shared_ptr<T> CreateObject(bool UseMemoryPool) 
     { 
      boost::shared_ptr<T> ptr((T*) mMemoryMgr->Allocate(sizeof(T),UseMemoryPool), &mMemoryMgr->Deallocate); 


      return ptr; 
     } 

    protected: 
     IMemoryManager* mMemoryMgr; 
    }; 

} 

#endif 

回答

7

shared_ptr希望刪除器是一個接受指針類型(T*)的單個參數的函數。您試圖將它傳遞給一個成員函數,並且由於shared_ptr沒有對IMemoryManager對象的引用,所以它不起作用。爲了解決這個問題,創建一個接受指針對象,並調用IMemoryManager ::解除分配()的靜態成員函數:

template <class T> 
static void Deallocate(T* factoryObject) 
{ 
    factoryObject->mMemoryMgr->Deallocate(); 
} 

然後,您可以創建你的shared_ptr這樣的:

boost::shared_ptr<T> ptr((T*) mMemoryMgr->Allocate(sizeof(T),UseMemoryPool), &IGameObjectFactory::Deallocate<T>); 
+0

我仍然得到以下錯誤:錯誤C2661:'boost :: shared_ptr :: shared_ptr':沒有重載的函數需要2個參數使用最新的boost版本 – KaiserJohaan 2012-03-31 19:03:54

+0

@KaiserJohaan:那麼,你使用的是什麼版本的Boost? – 2012-03-31 19:07:14

+0

我正在使用boost 1.49.0 – KaiserJohaan 2012-03-31 19:12:15

1

boost::shared_ptr,以及std::shared_ptr需要一個謂詞的定製刪除。所以你可以傳遞一個函數或函子。你傳遞的是一個指向成員函數的指針,由於沒有指向對象的指針,所以不足以調用它。詳情請參閱Pointers to member functions。有很多方法可以實現你想要的,我會編寫我自己的簡單仿函數來記錄一個對象工廠指針,並調用一個合適的方法來刪除它,一旦被shared_ptr調用。另外,考慮使用intrusive_ptr,除非你真的需要shared_ptr。它效率更高。