1

我有一个严重的问题,我使用默认构造函数来初始化对象,并使用带有参数的构造函数来复制 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();
}

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

4

2 回答 2

1

使用 ashared_ptr以便graphicDevice它只会在引用计数达到零时才被释放。首先,您不应该在析构函数中处理这个问题。

于 2013-02-24T04:46:40.863 回答
0

通过引用传递以减少副本、临时对象及其销毁的数量:

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

接着:

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

如果您想避免GraphicDevice为 的每个实例创建一个新的SpriteBatch,请GraphicDevice graphicDevice;参考:

GraphicDevice& graphicDevice;

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

于 2013-02-24T04:31:22.053 回答