What is the syntax for declaring a unique_Ptr variable in the header and then assigning it later in the constructor?

I coded the following and is very new to C ++, and it feels awkward. I am trying to provide a spriteBatch class (unique_Ptr). Here's the header file:

ref class CubeRenderer : public Direct3DBase { public: CubeRenderer(); ~CubeRenderer(); private: std::unique_ptr<SpriteBatch> spriteBatch; }; 

Then in the cpp constructor file this is:

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

It just seems awkward how I had to create "sb" and move it to "spriteBatch". The attempt to directly assign spriteBatch failed (maybe I just don’t know the correct syntax). Is there a way to avoid the need to use "sb" and std :: move?

Thanks.

+7
source share
1 answer

The following should work fine:

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

Alternatively, you can avoid duplicating the type name with the make_unique function .

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

Here is also a reset member :

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

But since you mention the constructor, why not just use a member initialization list?

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

All Articles