为什么在复制时会调用析构函数?

时间:2013-02-24 04:27:10

标签: c++

我有一个严重的问题,我使用默认构造函数初始化对象和带有参数的构造函数来复制DirectX接口。

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();
}

我希望在程序结束时调用析构函数,而不是在复制两个对象时调用析构函数。 我尝试重载赋值运算符和复制构造函数,但这对我没有帮助。 反正有吗?

2 个答案:

答案 0 :(得分:1)

shared_ptr使用graphicDevice,这样只有在引用计数达到零时才会释放它。你不应该首先在析构函数中处理这个问题。

答案 1 :(得分:0)

通过引用传递以减少副本数量,临时数量及其销毁情况:

void LoadContent(GraphicDevice& graphicDevice) 
{
    spriteBatch = SpriteBatch(graphicDevice); 
}

然后:

SpriteBatch::SpriteBatch(GraphicDevice& graphicDevice)
    :graphicDevice(graphicDevice)
{
}

如果您想避免为GraphicDevice的每个实例制作新的SpriteBatch,请将GraphicDevice graphicDevice;作为参考:

GraphicDevice& graphicDevice;

这需要在所有SpriteBatch构造函数中初始化。