c++constructorinitializationsmart-pointersinitialization-list

C++ - Run a function before initializing a class member


I have 2 resource managing classes DeviceContext and OpenGLContext both are members of class DisplayOpenGL. The resource lifetimes are tied to DisplayOpenGL. Initialization looks like this (pseudo code):

DeviceContext m_device = DeviceContext(hwnd);
m_device.SetPixelFormat();
OpenGLContext m_opengl = OpenGLContext(m_device);

The problem is the call to SetPixelFormat(), since I can't do that in the initializer list of the DisplayOpenGL c'tor:

class DisplayOpenGL {
public:
    DisplayOpenGL(HWND hwnd)
    : m_device(hwnd),
      // <- Must call m_device.SetPixelFormat here ->
      m_opengl(m_device) { };
private:
    DeviceContext m_device;
    OpenGLContext m_opengl;
};

Solutions that I can see:

Which of these solutions is preferable and why? Anything I am missing?

I'm using Visual Studio 2010 Express on Windows, if it matters.

Edit: I'm mostly interested in the tradeoffs involved in deciding for one of these methods.

Do I pretty much always want a smart pointer based solution in such cases anyway?


Solution

  • Comma operator to the rescue! An expression (a, b) will evaluate a first, then b.

    class DisplayOpenGL {
    public:
        DisplayOpenGL(HWND hwnd)
        : m_device(hwnd),
          m_opengl((m_device.SetPixelFormat(), m_device)) { };
    private:
        DeviceContext m_device;
        OpenGLContext m_opengl;
    };