C++无法返回纹理向量

C++ Can't Return A Vector of Textures

本文关键字:纹理 向量 返回 C++      更新时间:2023-10-16

我有一个类,可以跟踪我声明的对象。该课程还具有成员的向量。我通过功能添加纹理(可能有泄漏(。我可能对C 本身犯了一个错误,而不是SFML。

in item.h:

    #ifndef ITEM_H
    #define ITEM_H
    class ItemTexture {
        public:
            static std::vector<ItemTexture*> textures;
            std::vector<sf::Texture*> variation;
            ItemTexture(std::string file);
            void addTexture(std::string file);
            static sf::Texture getTexture(int id, int no) {
                return *textures[id]->variation[no]; //Program crashes here
            }
            static void declare_textures();
    };
#endif

在item.cpp中:

#include "Item.h"
std::vector<ItemTexture*> ItemTexture::textures;
ItemTexture::ItemTexture(std::string file)
{
    sf::Texture *tex = new sf::Texture;
    tex->setSmooth(false);
    tex->loadFromFile(file);
    variation.push_back(tex);
    textures.push_back(this);
    delete tex;
}
void ItemTexture::addTexture(std::string file)
{
    sf::Texture *tex = new sf::Texture;
    tex->setSmooth(false);
    tex->loadFromFile(file);
    variation.push_back(tex);
    delete tex;
}

这不给出任何错误消息,程序在行返回 *纹理[id] -> variation [no];

时崩溃

*textures[id]->variation[no];

中的代码中有两种可能性
  1. 您必须在堆栈中创建ItemTexture的对象,然后ItemTexture的构造函数将this指针推回向量textures。如果您创建的对象超出范围,则向量textures将具有一个悬空的指针,因为它指向的对象已经被破坏。或者,您可能会像使用SF ::纹理一样删除它,如下面的第二可能原因所述。这导致*textures[id]*textures[id]->variation[no];的一部分导致崩溃。

解决方案:动态分配它,不要删除它,直到您完成此操作(诸如getTexture()之类的调用(。

  1. 您是使用sf::Texture *tex = new sf::Texture;动态创建对象纹理,并用delete tex;删除该对象纹理。因此,无论使用variation.push_back(tex);推动什么推动,都会悬而未决的指针。variation充满了悬空的指针,当您访问它时,应用程序会崩溃。这会导致variation[no] *textures[id]->variation[no];的一部分导致崩溃,如果不是问题。

解决方案:删除delete tex;并将其释放到destructor中。