析构函数删除错误的元素
Destructor delete wrong element
我的纹理有一个小问题。
我想要那个:
- m_texture 具有 id 为 #5 的纹理
- 不应删除 ID 为 #5 的纹理。
问题:目前纹理#5被删除。
纹理在析构函数中删除了自身。
inline void SetTexture(Texture texture) //texture -> #5, m_texture -> #7
{
m_texture = texture;
//m_texture -> #5
//texture -> #5
// But #5 is deleted, and I don't want that
}
[...]
private:
Texture m_texture;
编辑:
这有效:
Texture texture(0, 102, 153);
rect.SetTexture(texture);
但这不会:
rect.SetTexture(Texture(0, 102, 153));
编辑2:我认为这个问题将结束,因为它涉及很多代码。[对不起]
纹理标题:
class Texture
{
public:
Texture(const std::string& fileName);
Texture(int red, int green, int blue);
void Bind();
virtual ~Texture();
protected:
private:
void Init(unsigned char* imageData, int width, int height);
GLuint m_texture;
};
纹理类:
Texture::Texture(const std::string& fileName)
{
int width, height, numComponents;
unsigned char* imageData = stbi_load((fileName).c_str(), &width, &height, &numComponents, 4);
if (imageData == NULL)
std::cerr << "Texture loading failed for texture: " << fileName << std::endl;
Init(imageData, width, height);
stbi_image_free(imageData);
}
Texture::Texture(int red, int green, int blue)
{
unsigned char imageData[] = {
static_cast<char>(red),
static_cast<char>(green),
static_cast<char>(blue)
};
Init(imageData, 1, 1);
}
void Texture::Init(unsigned char* imageData, int width, int height) {
glGenTextures(1, &m_texture);
glBindTexture(GL_TEXTURE_2D, m_texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, imageData);
}
Texture::~Texture()
{
glDeleteTextures(1, &m_texture);
}
void Texture::Bind()
{
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, m_texture);
}
似乎您的错误在于您如何为Texture
分配 ID。
由于您在销毁过程中进行了删除,因此必须在帖子中未共享的某个地方有指针。
纹理对象可能不遵循三法则。
如果你有一个副本、一个赋值或一个析构函数,那么你需要制作这三个。
演练您的代码当前正在执行的操作:
inline void SetTexture(Texture texture) //Texture::Texture(Texture) is called
{
m_texture = texture; //Texture::operator= is called
} //Texture::~Texture() is called
理想的行为是:
texture
中的 ID 应与作为参数传递的 ID 相同。- 该 ID 应传递给
m_texture
。 - 销毁
texture
时,它不是对 ID 的唯一引用,因此不会销毁它。
这是对shared_ptr
的内在使用.
相关文章:
- 从矢量中删除元素后出现隔离错误
- 删除映射和分割错误中的一个过去结束元素
- 在 alglib::real_1d_array 中获取元素总和的奇怪错误
- C++ - 将元素按升序插入数组的 SEG 错误
- 使用 <list> (错误 C2760) 打印队列的元素
- C++:使用类在向量中搜索特定元素时,我得到了错误的结果
- 用于查找数组中最大元素的出现次数的代码,给出分段错误
- C++ 将元素分配给映射值时访问错误
- 从加密项目向量中解密任意选择的元素会导致无效的 PKCS #7 块错误
- C++通过别名指针以静默方式将错误的类型分配给数组元素
- Leetcode 540 上的运行时错误.排序数组中的单个元素
- std::我不明白的矢量元素错误
- 如何修复从矢量中删除元素的错误?
- 为什么我在对向量的第二个元素"push_back"中有C3867错误
- 尝试访问 3D 矢量中的元素时出现 Seg 错误
- OpenCV 文件存储 - 错误:元素之间的解析错误 (icvYMLParseValue) 缺失
- 访问range_expression中的嵌套元素会返回不完整的映射(段错误)
- 打印向量元素错误消息
- 数组中的cout元素错误,错误
- 迭代并移除Vector中的元素.错误:Vector迭代器不可递增