C++ 不能 Return 纹理向量

C++ Can't Return A Vector of Textures

我有一个 class 可以跟踪我声明的对象。这个 class 也有一个向量作为成员。我通过一个函数添加纹理(可能有泄漏)。我可能对 c++ 本身做错了,而不是 sfml。

在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;
}

这不会给出任何错误消息,程序在 return *textures[id]->variation[no];

行崩溃

您的代码在 *textures[id]->variation[no];

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

解决方案:动态分配它并且在完成之前不要删除它(像 getTexture() 这样的调用)。

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

解决方案:删除delete tex;并在析构函数中释放它。