When I write C++ code I often try to limit the amount of header files that I have to #include
, because it keeps compilation time smaller and also prevent unnecessary recompilation of compilation units when part of my program changes.
On the other hand I also try to avoid managing the memory myself, and I prefer to use Object x;
instead of std::uniq_ptr<Object> x(new Object)
or Object *x
. But doing so implies that I have knowledge of the Object
's definition with the appropriate #include
in my header, as in the example below:
// Resources.h
#include <...> /* Include the header files needed to build an instance of Resources.
There quite be quite a lot of them, like some templated libraries, stuff that calls
upon some OpenGL functions, and so on. */
class Resources {
Rectangle rect;
Matrix<double> mat;
ImagePNG img;
public:
Resources(... /* give some parameters to initialize the resources */);
}
And now in another part of the program I have something like this:
// Application.h
#include "Resources.h" // <-- I want to get rid of this line
class Application {
Resources res;
public:
Application(... /* some parameters */);
}
So, as you can see, I would like to remove the line #include "Resources.h
. I know about forward declaration and I imagine I could do something like this:
// Application.h
class Resources;
class Application {
Resources *res;
public:
Application(... /* some parameters */);
}
But now my problem is how to manage the memory? I don't really want to be forced to write my own custom destructor/copy constructor/assignment operator every time I want to use a pointer instead of the whole object. And if I copy my instance of Application
, I want a full copy of res
to be created as well (so a std::shared_ptr<Resources>
wouldn't do: this is really object composition).
So I was wondering if anyone could give some advice in this kind of situation?