Summary: In this tutorial, we will learn the difference between strong reference and weak reference in C++.

Strong Reference

Sometimes in our program, we may have classes that refer to each other, for example:

Strong Reference

Here, class A and B are referring to each other using shared_ptr.

In case, if we create objects of both classes and later one of these objects goes out of scope, it is destroyed from the stack.

Though the object is deleted from the stack, the shared pointer which it was containing does not get destroyed because the memory allocated to it is on the heap.

The containing shared pointer will be destroyed only if the object to which it is pointing to, goes out of scope or deleted manually.

i.e. the object of class B will be completely destroyed only if the object pointed by shared_ptr<A> is deleted.

This one-to-one relationship between the classes keeps the other alive (i.e. A keeps B alive and B keeps A alive) and leaks the memory.

C++ Example: Strong Reference


C++ Strong Reference

Notice the output, although the objects of both the classes goes out of scope in the main method, neither the destructor of class A nor the destructor of class B was invoked.

This is because the strong reference cycle between objects prevents each other from being destroyed.

Weak Reference

The problem of the strong reference cycle can be easily solved with the help of weak pointer.

Only we need to decide who owns who?

Let say A owns B. If so, we replace the shared pointer in class B with a weak pointer.

Weak Reference

Now if the object of class B goes out of scope, the weak pointer will be destroyed irrespective of the fact the object which it is pointing to (instance of class A) is alive in the memory.

As a result, the object gets completely deleted both from the stack as well as from the heap, preventing memory leak.

Let’s see it practically in C++.

C++ Example: Weak Reference


C++ Weak Reference

Notice the output, this time the destructors of both the classes were invoked, proving the fact that both the objects which we have created in the method were completely destroyed.

This happened because we have defined weak reference between the classes using the weak_ptr.

That’s all for this discussion. Hope you got little idea about the difference between strong reference and weak reference in C++. Comment below if you have any doubts.

Leave a Reply

five × five =