Strong Reference

Sometimes when we design program, we may have two classes where each class refer to other. This implies one to one relationship between the classes and will be reflected in their objects when we instantiate them.

Take an example, we have two classes A and B, where

  • A refers to B.
  • B refers to A.
  • Share strong ownership using shared_ptr.

Strong Reference

Notice that A has shared pointer to B and B has shared pointer to A. When any of the objects goes out of scope, they will be destroyed from the stack but their shared resources on the heap will not be destroyed. Hence will leak memory.

A keeps B alive and B keeps A alive.

C++ Example of Strong Reference

Output

C++ Strong Reference

Notice the output, no destructor is being called because of strong reference cycle leading to memory leak i.e object not getting destroyed in heap.

Weak Reference

The above problem is often known as strong reference cycles. This can be easily solved using weak pointer. Only we need to decide who own who?

Let say A owns B. Then we replace shared pointer to A in class B with weak pointer. Now when B goes out of scope, it will be totally destroyed from the stack as well as heap memory. Therefore will not leak memory.

Weak Reference

C++ Example of Weak Reference

Output

C++ Weak Reference

Notice on using weak_ptr reference in class B, both classes destructors are being called because weak_ptr is weak reference and is destroyed automatically in the heap when the object containing reference goes out of scope.

That’s all for this discussion. Hope you got little idea about the difference between strong reference and weak reference in C++. If you have any doubt then do comment below.

Leave a Reply

Close Menu