Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the syntax to declare a unique_Ptr variable in a header, then assign it later in the constructor?

I have coded the following, and am very new to c++, and it feels clumsy. I am trying to give 'spriteBatch' (a unique_Ptr) class scope. Here's the header file:

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


private:

    std::unique_ptr<SpriteBatch> spriteBatch;

};

Then in the cpp file Constructor, this:

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

It just seems clumsy the way I had to create 'sb' and move it to 'spriteBatch'. attempting to assign directly to 'spriteBatch' failed (maybe I simply don't know the proper syntax). Is there a way to avoid needing to use 'sb' & std::move?

Thank you.

like image 983
Steve H Avatar asked Apr 29 '12 16:04

Steve H


People also ask

What is the constructor of unique_ptr<T>?

The constructor of unique_ptr<T> accepts a raw pointer to an object of type T (so, it accepts a T* ). The pointer is the result of a new expression, while in the second example: The pointer is stored in the pd variable.

What is the difference between unique_ptr and auto_ptr in C++?

This class template is deprecated as of C++11. unique_ptr is a new facility with a similar functionality, but with improved security. auto_ptr is a smart pointer that manages an object obtained via new expression and deletes that object when auto_ptr itself is destroyed.

How to destroy a dynamic object with a unique_ptr?

Thus, when you use a unique_ptr, you do not have to delete dynamically allocated objects, and the destructor of unique_ptr will take care of that. Below is an illustrated code that shows the scope outside which the pointer is destroyed. The object is destroyed when the control goes out of these curly braces.

What happens to a unique pointer when it is destructed?

If the unique pointer is destructed, the allocated object on the heap is destructed too { unique_ptr<int> p (new int); // make use of p } // p is destructed, so the int object is destructed. Compare the above code with raw pointers which are deleted explicitly by programmers. A unique pointer can also be created with std::make_unique


1 Answers

The following should work fine:

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

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

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

There's also the reset member:

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

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

CubeRenderer::CubeRenderer()
: spriteBatch(new SpriteBatch(m_d3dContext.Get())) {}
like image 80
R. Martinho Fernandes Avatar answered Sep 29 '22 10:09

R. Martinho Fernandes