Reputation: 21
I have a serious problem where I use the default constructor to initialize objects and a constuctor with parameters to copy a DirectX Interface.
SpriteBatch spriteBatch; //Creating an Object to SpriteBatch Class
//This Function Gets Called when Device is Created with Parameter to Device
void LoadContent(GraphicDevice graphicDevice)
{
/*Here is the Problem, When it Assigns to the Object it creates a Temp Object and
Destructor gets called where I free everything, I can't use the GraphicDevice after
this.*/
spriteBatch = SpriteBatch(graphicDevice);
}
//SpriteBatch Class
class SpriteBatch
{
GraphicDevice graphicDevice;
public:
SpriteBatch();
SpriteBatch(GraphicDevice graphicDevice);
~SpriteBatch();
}
SpriteBatch::SpriteBatch()
{
}
SpriteBatch::SpriteBatch(GraphicDevice graphicDevice)
{
this->graphicDevice = graphicDevice;
}
SpriteBatch::~SpriteBatch()
{
graphicDevice-Release();
}
I want the destructor to get called when my program ends and not when I copy two objects. I tried overloading the assignment operator and copy constructor which didn't help me though. Is there anyway to do that?
Upvotes: 1
Views: 126
Reputation: 97918
Use a shared_ptr
for the graphicDevice
so that it will only get released when the reference count reaches zero. You should not be dealing with this in the destructor in the first place.
Upvotes: 1
Reputation: 141780
Pass by reference to reduce the number of copies, temporaries and their destruction:
void LoadContent(GraphicDevice& graphicDevice)
{
spriteBatch = SpriteBatch(graphicDevice);
}
And then:
SpriteBatch::SpriteBatch(GraphicDevice& graphicDevice)
:graphicDevice(graphicDevice)
{
}
If you want to avoid making a new GraphicDevice
for each instance of SpriteBatch
, make GraphicDevice graphicDevice;
a reference:
GraphicDevice& graphicDevice;
This will need to be initialised in all of your SpriteBatch
constructors.
Upvotes: 0