Using smart pointers
Many languages support automated garbage collection. For example, memory acquired for an object is tracked by the runtime environment. It will deallocate the memory space after the object with a reference to it goes out of scope. Consider the following, for example:
// a code sample of the language (not-C++) supporting// automated garbage collection void foo(int age) { Person p = new Person("John", 35); if (age <= 0) { return; } if (age > 18) { p.setAge(18); } // do something useful with the "p" } // no need to deallocate memory manually
In the preceding code block, the p
reference (usually, references in garbage-collected languages are similar to pointers in C++) refers to the memory location returned by the new
operator. The automatic...