如何延迟成员变量的初始化

Sta*_*tec 1 c++

我有一个这样定义的Java类:

class GlslProgram
{
public:
    class Format {
    public:
        Format& vertex(const char* shader_path);
        std::string m_vertex_shader;

    private:
        std::string load_shader(const char* shader_path);
    };

    void use() const;
    void uniform(const GLchar* name, const GLboolean value) const;


    GlslProgram() {};
    GlslProgram(const Format& format, const bool separable = false);

private:
    GLuint m_handle;
    GLuint compile_shader(const std::string shader_string, const GLenum 
};
Run Code Online (Sandbox Code Playgroud)

第二个构造函数(即,GlslProgram(const Format& format, const bool separable = false);是我唯一想要使用或可用的构造函数。

我想删除默认的构造函数(或使其私有),但是不能这样做,因为我必须GlslProgram在应用程序中声明(未初始化的)实例作为另一个类的成员。

class BasicCubeExample : public Application
{
private:
    virtual void set_info()
    {
        Application::set_info();    
        m_info.title = "Basic cube example";
    }
    // Here the format is not yet known so I can not call the correct constructor (at this time)
    GlslProgram m_shader;
};
Run Code Online (Sandbox Code Playgroud)

因此,通过声明GlslProgram m_shader;我既调用了默认构造函数GlslProgram(我不想做),又不得不保持默认构造函数可用(我不想做)。

如何在不调用默认构造函数的情况下将类的实例声明为成员变量?

Rei*_*ica 5

一个解决方案(在注释和另一个答案中提到)是BasicCubeExample动态分配程序,并由智能指针保存它。

还有一种选择避免动态分配,即std::optional(或,在C ++ 17之前boost::optional):

class BasicCubeExample : public Application
{
private:
    virtual void set_info()
    {
        Application::set_info();    
        m_info.title = "Basic cube example";
    }
    // Here the format is not yet known so I can not call the correct constructor (at this time)
    std::optional<GlslProgram> m_shader;
};
Run Code Online (Sandbox Code Playgroud)

稍后,像这样初始化它:

m_shader.emplace(format, separable);
Run Code Online (Sandbox Code Playgroud)

之后,在使用中optional,使用*m_shader或就像指针一样取消引用m_shader->something