在我的代码中,我有动态分配的普通指针
class Texture
{
//code...
SDL_Texture* m_texture;
};
我从 Texture 类的 Init() 函数分配了 SDL_Texture*,并且析构函数释放了内存。
然而,这是一个问题。我不得不使用 shared_ptr,因为我对不同的对象使用相同的纹理,这些对象将被销毁,因此不允许我正确显示它们(在 vector 中的第一个对象被销毁后,纹理(为所有相同类型的对象共享) 消失了)。
所以我决定使用 shared_ptr,但我有一个问题 - 我不知道如何为 shared_ptr 分配一些东西:
//Old code:
m_texture = loadTexture();
//New code:
class Texture
{
std::shared_ptr<SDL_Texture> m_texture;
};
//code...
m_texture = loadTexture(); // Error! No assignment operator
我试过 .get() 函数,但它是右值,所以我不能给它赋值。有什么想法吗?
提前致谢。
最佳答案
您还需要一个自定义删除器:
#include <memory>
// Fake SDL library
typedef void SDL_Texture;
SDL_Texture* SDL_CreateTextureFromSurface(/*SDL_Renderer* , SDL_Surface* */) {
return 0;
}
void SDL_DestroyTexture(SDL_Texture* texture)
{}
// Shared
typedef std::shared_ptr<SDL_Texture> SharedTexture;
inline SharedTexture make_shared(SDL_Texture* texture) {
return SharedTexture(texture, SDL_DestroyTexture);
}
int main() {
SharedTexture texture;
texture = make_shared(SDL_CreateTextureFromSurface());
}
请注意,C 库:
- 可以使用不透明类型
- 自带删除功能或正在免费使用
关于c++ - 分配 std::shared_ptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18682868/