2013-02-24 71 views
1

我有一個嚴重的問題,我使用默認的構造函數來初始化對象和一個帶參數的構造函數來複制DirectX接口。爲什麼複製時調用析構函數?

SpriteBatch spriteBatch; //Creating an Object to SpriteBatch Class 

//This Function Gets Called when Device is Created with Parameter to Device 
void LoadContent(GraphicDevice graphicDevice) 
{ 
    /*Here is the Problem, When it Assigns to the Object it creates a Temp Object and 
    Destructor gets called where I free everything, I can't use the GraphicDevice after 
    this.*/ 

    spriteBatch = SpriteBatch(graphicDevice); 
} 


//SpriteBatch Class 

class SpriteBatch 
{ 
    GraphicDevice graphicDevice; 

    public: 
    SpriteBatch(); 
    SpriteBatch(GraphicDevice graphicDevice); 
    ~SpriteBatch(); 
} 

SpriteBatch::SpriteBatch() 
{ 
} 

SpriteBatch::SpriteBatch(GraphicDevice graphicDevice) 
{ 
    this->graphicDevice = graphicDevice; 
} 

SpriteBatch::~SpriteBatch() 
{ 
    graphicDevice-Release(); 
} 

我希望在程序結束時調用析構函數,而不是在複製兩個對象時調用析構函數。 我試圖重載賦值運算符和複製構造函數,但沒有幫助我。 有沒有辦法做到這一點?

+1

這是如何複製對象的作品。它的確如此簡單 – 2013-02-24 04:28:04

+0

如何在複製時不想讓析構函數調用? – user2028359 2013-02-24 04:30:21

回答

0

通過引用傳遞,減少拷貝,臨時對象的數量和他們的破壞:

void LoadContent(GraphicDevice& graphicDevice) 
{ 
    spriteBatch = SpriteBatch(graphicDevice); 
} 

然後:

SpriteBatch::SpriteBatch(GraphicDevice& graphicDevice) 
    :graphicDevice(graphicDevice) 
{ 
} 

如果你想避免新GraphicDeviceSpriteBatch每個實例,製作GraphicDevice graphicDevice;作爲參考:

GraphicDevice& graphicDevice; 

這將需要在所有SpriteBatch構造函數中初始化。

+0

我試過這個,但不幸的是,析構函數仍然被調用,破壞了GraphicDevice – user2028359 2013-02-24 04:39:29

+0

@ user2028359:***當***析構函數被調用了嗎?而且,它是調用析構函數的破壞而不是其他方式。 – Johnsyweb 2013-02-24 04:57:04

1

graphicDevice使用shared_ptr,以便僅當引用計數達到零時纔會釋放它。你不應該在析構函數中首先處理這個問題。

相關問題