C++无法返回纹理向量
C++ Can't Return A Vector of Textures
我有一个类,可以跟踪我声明的对象。该课程还具有成员的向量。我通过功能添加纹理(可能有泄漏(。我可能对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];
- 您必须在堆栈中创建
ItemTexture
的对象,然后ItemTexture
的构造函数将this
指针推回向量textures
。如果您创建的对象超出范围,则向量textures
将具有一个悬空的指针,因为它指向的对象已经被破坏。或者,您可能会像使用SF ::纹理一样删除它,如下面的第二可能原因所述。这导致*textures[id]
的*textures[id]->variation[no];
的一部分导致崩溃。
解决方案:动态分配它,不要删除它,直到您完成此操作(诸如getTexture()
之类的调用(。
- 您是使用
sf::Texture *tex = new sf::Texture;
动态创建对象纹理,并用delete tex;
删除该对象纹理。因此,无论使用variation.push_back(tex);
推动什么推动,都会悬而未决的指针。variation
充满了悬空的指针,当您访问它时,应用程序会崩溃。这会导致variation[no]
*textures[id]->variation[no];
的一部分导致崩溃,如果不是问题。
解决方案:删除delete tex;
并将其释放到destructor中。
相关文章:
- 写入向量<向量<bool>>
- 函数向量_指针有不同的原型,我可以构建一个吗
- std::向量与传递值的动态数组
- 将值指定给向量(2D)的向量中的某个位置
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 如何使用向量的template_back函数
- 尝试通过多个向量访问变量时,向量下标超出范围
- OpenInventor从9.8升级到10.4.2后,GLSL纹理返回零
- 如何通过派生类函数更改基类中的向量
- C++从另一个类访问公共静态向量的正确方法是什么
- 如何将ampl中的集合表示为c++中的向量
- 变量没有改变?通过向量的函数调用
- 迭代时从向量和内存中删除对象
- 向量 <int> a {N, 0} 和 int arr a[N] = {0} 的时间复杂度有什么区别
- 如何为模板化对象创建模板向量?VS正在投掷C3203
- 计算排序向量的向量中唯一值的计数
- 矩阵向量乘法(cublasDgemv)返回零
- 一对向量构造函数:初始值设定项列表与显式构造
- 将结构向量排序为子组
- C++无法返回纹理向量