我的纹理有一个小问题。
我想要那个:
- 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
的内在使用.