Typical and common references between objects are strong: If object A refers to object B by a strong reference, then object B can only be collected as garbage if object A is also being.
With weak references, the function is different: If object A refers to object B by a weak reference, then object B can be collected as garbage even if object A cannot be.
The purpose of using weak references is basically one: cache. For example, imagine that in your application you show several photographs that are read from files and that you are often showing the same images. It turns out that reading from a file over and over again is time consuming and inefficient as access to the disk is slow. Because of this, it is convenient to keep all these photos in memory, avoiding rereading them from the disk. However, by keeping all these photos in memory, you may end up consuming them completely, suffocating other running processes that need memory. So you’ll need some way to balance that, where photos are discarded from memory when they might be disrupting other processes.
That’s when the weak references come in. If you keep the images in memory through weak references, they will remain there as long as they are not disrupting other processes. From the moment we lack memory, before and the garbage collector throws a out-of-memory, it will try to clear some weak references to free up enough memory. In this case, your application will throw out of memory some of the stored images, which will need to be reread from the disk if they need to be accessed again.
The result is that your application will reach a balance where you can perform performance-based memory swaps automatically, managed by the garbage collector. It will consume more memory for better performance and sacrifice that performance when you need to save memory.
You are speaking of what is called "circular references" or "cyclic references". Most Garbage Collectors know how to treat cases properly. Life the section where @Maniero mentions me
– Jefferson Quesado
@Jefferson, thank you. I work mainly with C++ and use
std::shared_ptr
when want automatic collection. I did not know that the most modern collectors have already solved this problem.– Kyle A
"The reason I use weak references in C++ has to do with collection and reference cycles. For example, if A has a reference to B and B has a reference to A, the program can never collect the memory of A or B, because the two refer to "It doesn’t work, not even "forcing" memory collection through destructors and ?
– Igor PTZ
@Rogi93, The Purpose of Using
std::shared_ptr
is no need to worry about memory collection. If you need to force the collection, it means you are using the tools in a wrong way.– Kyle A