Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Before smart pointers came into being

Before smart pointers (capable of taking ownership of resources in the dynamic region and freeing them after use) came into being, I wonder how bookkeeping on dynamically created objects was performed when passed as arguments to functions that took resource pointers.

By bookkeeping, I mean that if there is a "new" then at some point later there should be a "delete" following it. Otherwise, the program will suffer from a memory leak.

Here is an example with B being a class and void a_function(B*) being a third party library function:

void main() {

  B* b = new B(); // line1

  a_function(b);  // line2

  ???             // line3
}

What do I do in line 3? Do I assume that the third party function has taken care of de-allocating the memory? If it has not and I assume that it has, then my program suffers from a memory leak. But, if it de-allocates the memory occupied by b and I too do it in main() so as to be on the safe side, then b actually ends up being freed twice! My program will crash due to a double-free error!

like image 872
softwarelover Avatar asked May 01 '26 06:05

softwarelover


1 Answers

The two core language features that enable "smart pointers", and more generally the idiom of scope-bound resource management (SBRM, sometimes also onomatopoeically referred to as RAII, for "re­source acquisition is initialization"), are:

  • destructors (automatic gotos)

  • unconstrained variables (every object can occur as a variable)

Both these are fundamental core features of C++ and have always been part of the language. Therefore, smart pointers have been always been imlpementable in C++.

[Incidentally, those two features mean that goto is necessary in C to handle resource allocation and multiple exits in a systematic, general fashion, while they are essentially forbidden in C++. C++ absorbs goto into the core language.]

Like with any language, it takes a long time before people learn, understand and adopt the "correct" idioms. Especially given the historic connections of C++ with C, lots of programmers who were and are working on C++ projects have come from a C background and have presumably found it more comfortable to stick with familiar patterns, which are still supported by C++ even though those are not advisable ("just replace malloc with new everyone and we'll be ready to ship").

like image 150
Kerrek SB Avatar answered May 03 '26 19:05

Kerrek SB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!