cxkernel

General notes during the development of cxkernel

Struct composition and ebl::RefPtr<T>

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:

struct Y {
    // ...
};

// Pointer to Y
struct X {
    struct Y* y;
};

// Embed Y directly
struct X {
    struct Y y;
};

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:

struct X {
private:
    struct Y y;
    // Fn's to use y
public:
    struct Y* 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.

Last updated