2012-04-29 15 views
7

我編寫了以下代碼,並且對於C++來說很新,而且感覺很笨拙。我試圖給'spriteBatch'(一個unique_Ptr)類作用域。這裏的頭文件:在頭文件中聲明unique_Ptr變量的語法是什麼,然後在構造函數中進行賦值?

ref class CubeRenderer : public Direct3DBase 
{ 
public: 
    CubeRenderer(); 
    ~CubeRenderer(); 


private: 

    std::unique_ptr<SpriteBatch> spriteBatch; 

}; 

然後在cpp文件構造函數,這樣的:

std::unique_ptr<SpriteBatch> sb(new SpriteBatch(m_d3dContext.Get())); 
spriteBatch = std::move(sb); 

這似乎只是笨拙的我要創建「SB」,並將其移動到「spriteBatch」的方式。試圖直接分配給'spriteBatch'失敗(也許我只是不知道正確的語法)。有沒有辦法避免需要使用'sb'& std :: move?

謝謝。

+0

如果這是在構造函數中,您可以使用成員初始值設定項。 – chris

+0

啊,謝謝,但實際上我的代碼不能編譯,所以我的問題有點不成熟。回到方格1. –

回答

8

以下應很好地工作:

spriteBatch = std::unique_ptr<SpriteBatch>(new SpriteBatch(m_d3dContext.Get())); 

或者,你能避免一些重複make_unique function類型名稱。

spriteBatch = make_unique<SpriteBatch>(m_d3dContext.Get()); 

另外還有reset member

spriteBatch.reset(new SpriteBatch(m_d3dContext.Get())); 

但是,既然你提到一個構造函數,爲什麼不直接使用成員初始化列表?

CubeRenderer::CubeRenderer() 
: spriteBatch(new SpriteBatch(m_d3dContext.Get())) {} 
+0

謝謝,但我必須做一些不正確的事情(可能在標題中)。大多數您列出的方法會產生以下編譯器投訴:cuberenderer.h(48):錯誤C2065:'SpriteBatch':未聲明的標識符 cuberenderer.h(48):錯誤C2065:'SpriteBatch':未聲明的標識符 cuberenderer.cpp 14):error C2663:'std :: unique_ptr <_Ty,_Dx> :: unique_ptr':7重載沒有'this'指針的合法轉換 –

+0

我缺少'using'指令。這給了我所有的編譯錯誤。一旦我過去了,你的所有方法都奏效了。謝謝!! –

+0

make_unique或初始化程序列表是否有區別?我對演出感興趣。 – JohnJohn

相關問題