0

I am following a "Learn OpenGL" book, and it is said that after linking individual shaders and compiling a shader program, we do not need the individual shaders anymore. Although it may be not entirely true in the more complex world of computer graphics, assume it is.

Now, when building the Shader and ShaderProgram classes, I want to implement this "destruct after not needed" behaviour, that is after ShaderProgram constructor finishes its job, vertex and fragment shader objects destructor should be called.

I can easily achieve such by using std::unique_ptr<Shader> and moving it into the ShaderProgram constructor.

I am just curious if there is a way to do it without using std::unique_ptr.

This is the example code I currently have:


class Shader {
public: 
    Shader(){\\creating a shader}
   ~Shader(){glDeleteShader(id);}
   /* some methods */
private:
    unsigned int id;
};

class ShaderProgram {
public: 
    ShaderProgram(std::unique_ptr<Shader> vertex, std::unique_ptr<Shader> fragment){\\create a shader}
   ~ShaderProgram(){glDeleteProgram(id);}
   /*some methods*/
private:
    unsigned int id;
};
naomipappe
  • 23
  • 1
  • 5
  • 6
    What's wrong with `unique_ptr`? It seems to be well suited to what you want to do. – cigien Nov 02 '20 at 22:42
  • There is nothing wrong with it, I simply was curious about the alternatives. – naomipappe Nov 02 '20 at 23:07
  • 1
    Ok, nothing wrong with being curious. I edited the question to make that a little clearer. Also, I removed the "thank you" part of the question. There's no harm in being polite, but for a Q&A site, it can be distracting, hope that's ok. Also, you might want to edit the question title, since it doesn't really summarize the question you're asking. – cigien Nov 02 '20 at 23:12
  • 1
    To create an object and immediately destroy it, just “call” the constructor: `MyType(whatever);`. – Pete Becker Nov 03 '20 at 01:08
  • 1
    Yes, there is a way to do it without smart pointers. Incorporate move semantics in the Shader object itself. – n. m. could be an AI Nov 03 '20 at 10:27

1 Answers1

1

Just call glDeleteShader(id) after you link it in your ShaderProgram constructor, no need to define a Shader class to hold this temporary object.