Reputation: 1265
I recently started to learn OpenGL (ver. 3.3 to be specific) and I also wanted to use some object oriented design for some features. For example, I want to create a class called Shader that reads the shader from a text file, attach, detach it etc. The problem I have is the destructor. I suppose all OpenGL objects work more or less like that
glCreateShader()
// some code here
glDeleteShader()
Lets say I design my class like this (this is just a sketch so without any details)
class Shader
{
public:
// read from file - not important right now
Shader( ){}
void delete()
{
glDeleteShader();
}
~Shader()
{
glDeleteShader();
}
};
I could create my object and delete it like this
Shader x;
x.delete();
but this will not delete the object itself - only frees the memory of OpenGL shader. It would be better to have something like this
Shader x;
delete(x);
where function delete() removes everything from the memory (with the object itself). Is it possible, or should I only use pointers?
Shader* x = new Shader();
delete x;
I have the same problem for any C library.
Upvotes: 0
Views: 143
Reputation: 238321
I could create my object and delete it like this
Shader x; x.delete();
Firstly, delete
is a keyword, so it may not be the name of a function.
Assuming it is OK to call glDeleteShader
twice, this is OK. But the call to delete()
function is redundant, since the destructor handles the call to glDeleteShader
automatically. If duplicate calls to glDeleteShader
is not OK, then calling delete()
is not only redundant, but a bug.
Shader x; delete(x);
where function delete() removes everything from the memory (with the object itself). Is it possible ...
It is not possible to remove an object of automatic storage duration from memory by calling a function (unless you replace the storage with a fresh object, but that's way off topic to this question). Automatic objects are removed form memory... automatically when they go out of scope.
or should I only use pointers?
No, unless you need to. If automatic objects are an option, they are the better option. Simply do this:
Shader x;
// glDeleteShader called when x is destroyed
Upvotes: 1