You need to enable JavaScript to run this app. SDL2无法渲染vector中存储的Entity实体 屏幕黑屏问题求助
优惠活动
大模型
产品
解决方案
定价
更多

SDL2无法渲染vector中存储的Entity实体 屏幕黑屏问题求助

问题原因

你的问题核心是Entity类的生命周期设计和std::vector的拷贝机制冲突:

  • 你在Entity的析构函数中调用了SDL_DestroyTexture销毁纹理,而std::vector<Entity> entities = {Entity(Vec2i{5, 5}, r.CreateTexture("res/gfx/bob.png"))};这行代码会先构造一个临时Entity对象,再将这个临时对象拷贝到vector的存储空间中,随后临时对象生命周期结束,自动触发析构函数,把刚加载的纹理直接释放了。
  • 此时vector里存储的Entity对象持有的纹理指针已经是野指针,调用渲染接口时传入无效纹理,自然只会显示黑屏。
  • 单独声明的bob对象没有拷贝销毁的过程,直到程序退出时才会析构,所以纹理一直有效,渲染正常。
解决方案

你可以根据需求选择以下任意一种修复方式:

方案1:为Entity实现移动语义(最简单的快速修复)

禁止Entity的拷贝,实现移动构造和移动赋值函数,将临时对象的纹理所有权转移到vector中的对象,避免临时对象析构时销毁正在使用的纹理:

// 在entity.h的Entity类声明中添加:
Entity(const Entity&) = delete; // 禁止拷贝构造
Entity& operator=(const Entity&) = delete; // 禁止拷贝赋值
Entity(Entity&& other) noexcept;
Entity& operator=(Entity&& other) noexcept;

// 在entity.cpp中实现:
Entity::Entity(Entity&& other) noexcept : pos(other.pos), texture(other.texture) {
    other.texture = nullptr; // 临时对象的纹理指针置空,析构时不会销毁
}

Entity& Entity::operator=(Entity&& other) noexcept {
    if (this != &other) {
        SDL_DestroyTexture(texture); // 先释放当前对象持有的纹理
        pos = other.pos;
        texture = other.texture;
        other.texture = nullptr;
    }
    return *this;
}

修改后初始化vector时改用emplace_back避免临时对象生成:

std::vector<Entity> entities;
entities.emplace_back(Vec2i{5, 5}, r.CreateTexture("res/gfx/bob.png"));

方案2:vector存储智能指针避免拷贝

如果不想修改Entity类,可以把vector的存储类型改为智能指针,避免Entity对象的拷贝操作:

std::vector<std::unique_ptr<Entity>> entities;
entities.push_back(std::make_unique<Entity>(Vec2i{5, 5}, r.CreateTexture("res/gfx/bob.png")));

// 渲染时的遍历也对应修改:
for (const auto& e : entities) {
    r.RenderEntity(*e);
}

方案3:抽离纹理管理逻辑(长期最优)

当前的设计中每个Entity都负责销毁自己的纹理,如果多个Entity共用同一张纹理,只要其中一个销毁,其余Entity的纹理指针都会失效。更合理的设计是单独实现纹理管理器,统一负责纹理的加载、复用和销毁,Entity只持有纹理的引用/ID,不负责纹理的生命周期管理,从根源上避免这类问题。

内容的提问来源于stack exchange,提问作者Max Drießen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 16:27:02