Ok, so I think I understand RAII. I think I have an idea what exception safety is about too.
In order to conform to RAII, and in an attempt to make my code more exception safe, I have attempted to remove a margin for error from my cMain class. Before, it would have an ordinary private member of type cD3D, which I would then call Initialize(HWND) on in the constructor of cMain, after creating my HWND object.
Of course, this to some extent defies the point of RAII in that cD3D is defined as such
class cMain
{
public:
cMain(HINSTANCE hInstance, LPTSTR applicationName);
private:
cD3D m_d3d;
};
(I have trimmed some of the other members as they aren't relevant to this query)
and cMain is constructed as follows:
cMain::cMain(HINSTANCE hInstance, LPTSTR applicationName)
{
m_hInstance = hInstance;
m_applicationName = applicationName;
m_hWnd = CreateNewWindow(hInstance, applicationName);
m_d3d.Initialize();
}
and thus acquires the resources for m_d3d when cMain is constructed. Initialize is then called separately. I don't like this and never have, because it leaves the idea open that somewhere someone may forget to Initialize an object and therefore exceptions may be thrown. In this case, it's not particularly bad because I make sure it's all wrapped up before anything happens, but I do often worry about adding checks to ensure an object is Initialized before it is used. I have also privatised the default constructor and the copy constructor, so they cannot be used, to ensure that making the object always initializes it properly.
I have then changed it to the following:
class cMain
{
public:
cMain(HINSTANCE hInstance, LPTSTR applicationName);
private:
cD3D& m_d3d;
};
cMain::cMain(HINSTANCE hInstance, LPTSTR applicationName)
:
m_hInstance(hInstance),
m_applicationName (applicationName),
m_hWnd(CreateNewWindow(hInstance, applicationName)),
m_d3d(*new cD3D(m_hWnd))
{
}
For some reason, this feels safer, except for the new cD3D(m_hWnd) and dereferencing it.
Is this correct practice for RAII? Should doing this for other classes reduce my exposure to exceptions? Aside from anything else, I have had to alter the way cD3D is stored in cMain as I have made the copy constructor of cD3D inaccessible (for the same reasons) and as such have had to change
cD3D m_d3d;
to
cD3D& m_d3d;
I know it's a silly question but am I heading in the right direction? I'm learning a lot of new skills to make sure this game is written well from the start