I have a parent object that has some other objects as fields. The parent object fully owns these fields: they can be declared as fields of the parent object (MyPart part
), directly, not as references.
I would prefer to initialize these fields in constructor, but in some cases they do need to reach the parent object instance and call methods on it as they work. With raw pointers, I could simply pass this
to they constructors or setters. I have just discovered however that creating smart pointer from this
is something near impossible, because such pointer would not know when the parent object goes out of scope (for sure not where the constructor returns!). But I do known that being the fields of the parent object, these children definitely cannot outlive it.
The only "clean" idea I can so far imagine is to construct the object in some factory method where reference to the constructed parent can be a smart pointner, then construct children separately and use the setter to compose the parent. Is this really the best approach?
As we have now policy to avoid raw pointers at all costs, what other options could I have? Or just using raw pointers in such a case is appropriate?
Parent&
, and pass it*this
if you truly need access to the parent. If the child needs access to the parent through astd::shared_ptr<>
, you can have the parent inheritstd::enable_shared_from_this
see here. This will allow ashared_ptr
to be constructed bythis->shared_from_this()
. Unless you are implementing a data structure this is almost certainly poorly designed. Whateverchild
needs ofParent
try and extract it into a common class, this way it can be fully constructed before use.