【发布时间】:2019-01-30 19:14:16
【问题描述】:
在我的资源管理器中,createTexture 方法应该生成一个指向纹理的指针。当只有经理拥有资源时,我想删除它。我怎样才能做到这一点?如果我使用 shared_ptr,资源管理器会将其 shared_ptr 指针存储到纹理中,并且无法删除它。
class ResourceManager
{
vector<shared_ptr<Texture>> _textres;
public:
shared_ptr<Texture> CreateTexture()
{
auto tex = shared_ptr<Texture>(new Texture);
_textures.push_back(tex);
return tex;
}
}
int main
{
ResourceManager rm;
{
auto tex = rm.CreateTexture();
// Do something with texture...
}
// Problem here: ResourceManager doesn't remove the texture because he owns it
}
【问题讨论】:
-
经理为什么要坚持贴图?
-
你想要
std::weak_ptr吗? -
一种方法(假设您不能完全摆脱
_textures向量)是让_textures持有weak_ptr<Texture>类型的对象,而不是shared_ptr<Texture>。 en.cppreference.com/w/cpp/memory/weak_ptr -
资源管理器必须知道所有纹理的内存使用情况。我还想在删除纹理时(在另一个线程中异步)做一个特殊的逻辑。
-
所以你只是想让资源管理器在纹理被其他地方删除时以某种方式得到通知,而不是真正让它保持活动状态?你的特殊逻辑应该在哪个线程中执行?
标签: c++