为什么复制时调用析构函数?
我有一个严重的问题,我使用默认的构造函数来初始化对象和一个带参数的构造函数来复制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();
}
我希望在程序结束时调用析构函数,而不是在复制两个对象时调用析构函数。 我试图重载赋值运算符和复制构造函数,但没有帮助我。 有没有办法做到这一点?
通过引用传递,减少拷贝,临时对象的数量和他们的破坏:
void LoadContent(GraphicDevice& graphicDevice)
{
spriteBatch = SpriteBatch(graphicDevice);
}
然后:
SpriteBatch::SpriteBatch(GraphicDevice& graphicDevice)
:graphicDevice(graphicDevice)
{
}
如果你想避免新GraphicDevice
为SpriteBatch
每个实例,制作GraphicDevice graphicDevice;
作为参考:
GraphicDevice& graphicDevice;
这将需要在所有SpriteBatch
构造函数中初始化。
我试过这个,但不幸的是,析构函数仍然被调用,破坏了GraphicDevice – user2028359 2013-02-24 04:39:29
@ user2028359:***当***析构函数被调用了吗?而且,它是调用析构函数的破坏而不是其他方式。 – Johnsyweb 2013-02-24 04:57:04
对graphicDevice
使用shared_ptr
,以便仅当引用计数达到零时才会释放它。你不应该在析构函数中首先处理这个问题。
这是如何复制对象的作品。它的确如此简单 – 2013-02-24 04:28:04
如何在复制时不想让析构函数调用? – user2028359 2013-02-24 04:30:21