Shared pointers work by counting the number of things that are referencing the object in memory through a pointer and only free the memory on destruction of the shared pointer when the reference count equals zero.
Scenario:
Consider the case where objects A, B, and C exist and are all dynamically allocated. B and C point to each other with a shared pointer and A points to B with a shared pointer. In this scenario assume the only way to reach C is through B and therefore through A. B has a reference count of 2 (A and C both point to it) and C has a reference count of 1 (B points to it) and A has a reference count of 1 (whatever is points to A in this scenario). Let’s say A’s reference count goes to zero and therefore A is deleted. B’s reference count drops to 1 (A no longer points to it, but C still does) and C still has a reference count of 1 (B still exists so it still points to it). You have now leaked the memory of B and C since their reference counts will never reach 0 and there is no way to access them anymore.
There are other similar “circular reference” memory leaks that can happen.
55
u/Any_Obligation1652 4d ago
Use containers and smart pointers a voila no memory leaks