- There is a master class M that need access to an object (instance) of O.
- M is the only one that needs the access.
- O shall be allocated with M, and destroyed with M.
- O is not very big and has a trivial constructor that will never fail.
- O and M are different enough so as not to warrant a merge.
There are a couple of ways to do this (and possible more):
- M allocates (using new) a pointer to the O instance. It has to be deleted with the destruction of M.
- M uses std::unique_ptr<> to the O instance. A call to "new" is still needed, but destruction will be automated.
- The O instance is declared as a member of M.
I suppose alternative 2 is usually to prefer before alternative 1. But the choice between 2 and 3 is harder.
Instinctively, I prefer option 3. That way, I don't need to bother with dynamic allocation. But the drawback is that the declaration of O has to go into the header file of M (whereas only a forward declaration is needed for alternative 1 and 2). If there is a complex data hierarchy, it can all end up (indirectly) with a lot of includes in the top-most type. And that does not "feel right".
I usually follow the pattern to have a trivial constructor that only makes sure everything is cleared, and then a Init-function that do the real initiation (which can also return a failure).