【发布时间】:2019-11-15 09:17:01
【问题描述】:
我有一个类来跟踪我声明的对象。这个类也有一个向量作为成员。我通过函数添加纹理(可能存在泄漏)。我可能对 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];
行【问题讨论】:
-
那是因为你把纹理推回向量后删除了,所以向量包含了所有删除的Texture*。
-
这不会给出任何错误信息——这意味着C++代码是有效的。与程序逻辑是否正确无关。
-
@PaulMcKenzie 甚至没有。显然,OP 删除了一些东西然后引用了它,这是 UB,因此不正确的 C++ 代码。无错误编译是保证代码中不存在非常狭窄的一类问题。
-
而 C++ 允许这样不完美的代码无错误地编译。我看到很多新手发布“它编译好,但是......”这一行,好像“它编译好”真的意味着什么。
-
“这不会给出任何错误消息,” - 不幸的是,没有编译器警告/错误确实不意味着您的代码是有效的或做任何合理的事情。在 C++ 中有 很多 的东西可以让你编写并且编译器会编译,但这些东西仍然是荒谬的或具有未定义的行为(不需要诊断)。 “它编译”是一个非常低的正确性标准,并且远远不足以显示没有错误。