gpt4 book ai didi

c++ - 为什么复制时会调用析构函数?

转载 作者:太空宇宙 更新时间:2023-11-04 11:58:45 25 4
gpt4 key购买 nike

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

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

最佳答案

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

关于c++ - 为什么复制时会调用析构函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15048664/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com