Consider two structures X, Y where Y needs to be a part of X. We can either embed Y directly in X or keep a pointer to Y in X:
structY{// ...};// Pointer to YstructX{structY*y;};// Embed Y directlystructX{structYy;};
We may even recognize that embedding Y directly in X is slightly more performant as it may result in 1 less dereference. Which approach should we take? Here is a rule of thumb to follow:
We should always use RefPtr<T> to track child structs unless we can guarantee we never need to publicly "share" pointers to the child member.
For example:
structX{private:structYy;// Fn's to use ypublic:structY*getY();};c++
In this case, it is better to convert y into a RefPtr<Y> because when we lend out pointers to y via getY(), we implicitly increase the reference count of X. Otherwise, we can easily end up with a use-after-free scenario, where X is freed but the pointer to y remains live.