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.
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.
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.
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.
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
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())) {}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With