I was looking for an alternative to using so many shared_ptrs and found a great answer in the comments section:
Do you really need a joint ownership? If you stop and think about a few minutes, I’m sure that you can precisely determine one owner of the object and a number of users who will use only this during the life of the owner. So just make it a local / member owner object and pass links to those who should use it.
I would love to do this, but the problem is that defining the owner object now requires that the object that needs to be fully defined is fully defined. For example, let's say I have the following in FooManager.h:
class Foo;
class FooManager
{
shared_ptr<Foo> foo;
shared_ptr<Foo> getFoo() { return foo; }
};
Now, taking the advice above, FooManager.h becomes:
#include "Foo.h"
class FooManager
{
Foo foo;
Foo& getFoo() { return foo; }
};
I have two problems with this. Firstly, FooManager.h is no longer easy. Each cpp file that includes it should now also compile Foo.h. Secondly, I no longer need to choose when foo is initialized. It must be initialized simultaneously with FooManager. How do I get around these issues?
source
share