There is nothing which is fundamentally flawed about this idea. What you have is two relationships. Boss
owns one or more Worker
s. And Worker
has a non-owning reference to a Boss
. The use of a raw pointer suggests that Worker
does not own the pointer it stores; it's merely using it. This means that it does not control that object's lifetime.
There is nothing wrong with such a relationship per-se. It all depends on how it gets used.
For example, if the Boss
reference that Worker
stores is the actual Boss
object instance that owns the Worker
, then everything is fine. Why? Because presumably, a Worker
instance cannot exist without a Boss
who owns it. And because the Boss
owns it, this guarantees that the Worker
will not outlive the Boss
it references.
Well... kinda. And this is where you start getting into potential problems.
First, by the rules of C++ construction, Boss::worker
is constructed before the Boss
instance itself. Now, Boss
's constructor can pass a this
pointer to Worker
's constructor. But Worker
cannot use it, since the Boss
object has not yet been constructed. Worker
can store it, but it can't access anything in it.
Similarly, by the rules of C++ destruction, Boss::worker
will be destroyed after the owning Boss
instance. So Worker
's destructor cannot safely use the Boss
pointer, since it points to an object whose lifetime has ended.
These limitations can sometime lead to having to use two-stage construction. That is, calling Worker
back after Boss
has been fully constructed, so that it can communicate with it during construction. But even this may be OK, particularly if Worker
doesn't need to talk to Boss
in its constructor.
Copying also becomes a problem. Or more to the point, the assignment operators become problematic. If Worker::boss
is intended to point back to the specific Boss
instance that owns it, then you must never copy it. Indeed, if that's the case, you should declare Worker::boss
as a constant pointer, so that the pointer gets set in the constructor and nowhere else.
The point of this example is that the idea you've defined is not, by itself, unreasonable. It has a well-defined meaning and you can use it for many things. You just have to think about what you're doing.