Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what exactly reference counting in c++ means?,

What exactly is reference counting? In particular, what is it for C++? What are the problems we can face if we don't handle them? Do all languages require reference counting?

like image 572
Naruto Avatar asked Apr 06 '12 19:04

Naruto


2 Answers

What exactly is reference counting? In particular, what is it for C++?

In simple words, Reference counting means counting the references to an object.

Typically, C++ employs the technique of RAII. Wherein, the ability to manage the deallocation of an type object is tied up within the type object itself. It means that the user does not have to explicitly manage the lifetime of the object and its deallocation explicitly, The functionality to do this management is built in the object itself.

This functionality means that the object should exist and remain valid untill there are stakeholders who refer to the object, and this is achieved by reference counting. Everytime the object is shared(copied) the reference count(typically a member inside the class type) is incremented and each time the destructor is called the count is decremented, when the count reaches 0, the object is not being reffered by anyone and it marks the end of its lifetime and hence it is destructed.

What are the problems we can face if we don't handle them?

It would mean no more RAII, and endless and often faulty manual resource management.
In short programming nightmares.

Do all languages require reference counting?

Languages don't require reference counting but employing the technique provides very easy usage and less efforts for users of the language, So most languages prefer to use it to provide these advantages to their users.

like image 82
Alok Save Avatar answered Oct 18 '22 13:10

Alok Save


Reference counting is a simple but not complete approach for garbage detection.

When the counter reaches zero, you could release that object.

BUT if there are no more used objects which referencing each other cyclic, they will never be released

Consider a references b, b references a, but nothing else reference a or b. The reference count on a and b will be still 1 (= in use)

like image 42
stefan bachert Avatar answered Oct 18 '22 13:10

stefan bachert