Is there a principle for choosing between embedding a struct itself or the pointer to a struct inside a struct?

  c++, pointers, struct

This is a code snippet from qemu.(qemu-5.1.0 include/hw/arm/smmu-common.h)

typedef struct SMMUDevice {
    void               *smmu;
    PCIBus             *bus;
    int                devfn;
    IOMMUMemoryRegion  iommu;
    AddressSpace       as;
    uint32_t           cfg_cache_hits;
    uint32_t           cfg_cache_misses;
    QLIST_ENTRY(SMMUDevice) next;
} SMMUDevice;

I’ve seen many such codes until now but I am now curious if there is any principle/rule in choosing between

  1. embedding a struct A inside a struct B
  2. embedding a pointer to the struct A inside a struct B
    Two things that come to my mind right away is that if a struct A is to be shared by many structs, it is better to use pointer. or if the struct containing the struct(that is, struct B) is to be frequently passed as a function argument, it would be better to use pointer(pointer to struct B as argument, or pointer to A inside struct B and struct B is the argument) because copying the struct to stack would take long time.

I am curious if there are other important rules.

Source: Windows Questions C++

LEAVE A COMMENT