在头中声明unique_Ptr变量的语法是什么,然后在构造函数中稍后赋值?

Ste*_*e H 7 c++-cli unique-ptr

我编写了以下代码,对c ++来说很新,而且感觉很笨拙.我试图给'spriteBatch'(unique_Ptr)类范围.这是头文件:

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


private:

    std::unique_ptr<SpriteBatch> spriteBatch;

};
Run Code Online (Sandbox Code Playgroud)

然后在cpp文件构造函数中,这个:

std::unique_ptr<SpriteBatch> sb(new SpriteBatch(m_d3dContext.Get()));
spriteBatch = std::move(sb);
Run Code Online (Sandbox Code Playgroud)

它只是看起来笨拙的方式我必须创建'sb'并将其移动到'spriteBatch'.试图直接分配给'spriteBatch'失败(也许我只是不知道正确的语法).有没有办法避免需要使用'sb'和std :: move?

谢谢.

R. *_*des 8

以下应该工作正常:

spriteBatch = std::unique_ptr<SpriteBatch>(new SpriteBatch(m_d3dContext.Get()));
Run Code Online (Sandbox Code Playgroud)

或者,您可以避免使用某些make_unique功能重复类型名称.

spriteBatch = make_unique<SpriteBatch>(m_d3dContext.Get());
Run Code Online (Sandbox Code Playgroud)

还有reset会员:

spriteBatch.reset(new SpriteBatch(m_d3dContext.Get()));
Run Code Online (Sandbox Code Playgroud)

但是,既然你提到了一个构造函数,为什么不使用成员初始化列表呢?

CubeRenderer::CubeRenderer()
: spriteBatch(new SpriteBatch(m_d3dContext.Get())) {}
Run Code Online (Sandbox Code Playgroud)