When is it worth using a pointer to a struct in a structure definition?

Sorry if the question is not clear; It was very difficult for me to explain in one sentence.

Say I have a struct with an element that is a struct , for example. following:

 struct A { struct B b; }; 

Suppose I assume that instances of this structure will always be distributed in heaps. Is there something you can get by changing this to this? (i.e. holding the pointer to struct B )

 struct A { struct B *b; }; 

In the latter case, I would have several functions, such as make_A and free_A , that were free_A allocating and de-allocating the memory pointed to by b ;

The only example I can imagine where the second form may be preferable is when not all instances of struct A actually use b . In this case, the memory can be saved by allocating additional memory for those instances that require it.

Are there other cases where the second form offers something useful?

+4
source share
3 answers

If each A will have exactly one B , you should not use a pointer to B

Besides the fact that you don’t need to worry about additional memory management, it is actually slower and less efficient to allocate B

Even if you want to pass the pointer to B to another code, you can still pass this address.

+7
source

When an instance of B can be used by multiple instances of A, you get its pointer to B. This helps to avoid duplication and maintain versions of B in more than one place. According to Jonathan, this is because you need to know when to free up memory and references to B.

+5
source

I think you hit a nail on the head with your last expression. If not every A has B , then you can get the storage using the pointer (null for those A without B ).

This is unlikely to be really useful if the cumulative size of all unused B is a significant fraction of the available heap.

But I would modify your statement to read β€œwhen not all instances of A will have exactly one copy of B ” for the following reason (and this is another case that you are asking):

Where B is a node in the list (which also contains a pointer to another B or null), I would make it a pointer [although you could still inline the first node if all A should have at least one B ].

Another possibility is to distribute B among A if their nature allows (for example, A be windows on screen B ), although you will have to refer to account B in this case to find out when to finally free them in your free_A() calls (and, of course, be able to reuse an existing B in your make_A() calls).

+3
source

All Articles