How to use references, avoid header bloat, and delay initialization?

Posted by Kyle on Stack Overflow See other posts from Stack Overflow or by Kyle
Published on 2010-03-25T02:01:35Z Indexed on 2010/03/25 2:03 UTC
Read the original article Hit count: 397

I was browsing for an alternative to using so many shared_ptrs, and found an excellent reply in a comment section:

Do you really need shared ownership? If you stop and think for a few minutes, I'm sure you can pinpoint one owner of the object, and a number of users of it, that will only ever use it during the owner's lifetime. So simply make it a local/member object of the owners, and pass references to those who need to use it.

I would love to do this, but the problem becomes that the definition of the owning object now needs the owned object to be fully defined first. For example, 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 issues with this. First, FooManager.h is no longer lightweight. Every cpp file that includes it now needs to compile Foo.h as well. Second, I no longer get to choose when foo is initialized. It must be initialized simultaneously with FooManager. How do I get around these issues?

© Stack Overflow or respective owner

Related posts about c++

Related posts about references