c++ - 分配 std::shared_ptr

标签 c++ pointers c++11 std shared-ptr

在我的代码中,我有动态分配的普通指针

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/

相关文章:

C++ - 查找倍数并消除常见的

c++ - 在 C++ 应用程序中使用库的良好跨平台功能语言?

c++ - 为什么 C++ 中 auto_ptr 的二维 vector 不起作用?

c++ - 将文件存储在 unsigned char 数组中并打印

c++ - 如何默认初始化 C++ 中内置类型的局部变量?

c# - 了解 C++ DLL 使用 union 映射到 C#

将 u_int32_t 转换为 char **

C++ lambda 表达式 : captured pointer to STL container changing address after pop?

C++11 嵌套 std::conditional

C++ 统一赋值运算符移动语义