For C and C++, linked list with a pointer pointing to its head node. But, all nodes are allocated on heap by malloc() or new. When the head pointer runs out of its scope e.g. its function exits, all nodes allocated on heap will be lost. Right? Is this a memory leak?
How C/C++ handle this kind of issue? It calls deallocator automatically? (e.g. free() or delete)?
The better way to handle this sort of thing is to use a standard container, instead of some homespun thing, unless you have good reason & know what you’re doing, and why…
std::vector<>
std::list<>
But to choose a container, it’s important to know what you’re doing, what the lifetime is supposed to be.
@Jack – no matter what you do, standard containers don’t magically take care of manually allocated objects for you. That is fundamentally impossible.
You must change your approach to the problem to perceive the problem as “manually allocated objects.” Once you make this leap, and realize that this is a bad way to go, then you can choose between “they’re value-objects” or “they’re to be managed by shared_ptr”.
EX1: using shared_ptr to hold new’d objects (this is the approach to use if copying around MyNode is a bad idea [performance, owned resources, preserved state]):
EX2: This is what you do if your nodes are cheap, can be treated as copyable objects (value semantics):
And if you really would rather manage the instances manually for some reason (usually you do this because the lifetimes are not really tied to a single container’s lifetime, but have some irregular lifecycle that cannot be encapsulated neatly by anything but a custom algorithm):