- Is C++ a System Language?
- Memory Management Guidelines for malloc, calloc, realloc
- C++ 11 and Memory Management: Unique Pointers
- Conclusion
C++ 11 and Memory Management: Unique Pointers
Unique pointers are a welcome addition to C++ 11. Simply put, unique pointers are classes that provide for what can be called deterministic allocation. In some respects, unique pointers resemble a common design pattern called the façade. In the façade pattern, a complex system with one or more interfaces is modeled as a much simpler class. The latter class then abstracts much of the complexity of the wrapped class. The unique pointer class does something notionally similar.
Let's see some typical uses of unique pointers.
Unique Pointers and Deleters
Remember in the earlier discussion, we had to concern ourselves with maintaining state and then deallocating memory based on that state? Well, this type of detail is no longer necessary when you employ unique pointers. Instead, the wrapper class takes care of this issue automatically, thereby freeing you from many legacy memory-allocation issues. Listing 8 illustrates an example of a simple use of a unique pointer.
Listing 8Creating and using a C++ 11 unique_ptr.
unique_ptr<Person> createPerson() { unique_ptr<Person> p(new Person("Johnny Doe", 100)); cout << "Person just created is: " << p->getName() << endl; return p; } void getPersonDetails() { unique_ptr<Person> person = createPerson(); cout << "Person name = " << person->getName(); // Get the person's name // The person object is now destroyed on exit }
In Listing 8, the createPerson() function creates an instance of the Person class using a unique_ptr. Notice how the function getPersonDetails() uses the person object. No need to worry about destructors: Everything gets cleaned up thanks to the unique_ptr wrapper class.
Listing 9 shows a complete run of all the code in the article:
Listing 9A complete program run
Function name: aMemoryLeak() a = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa b = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb New version of a = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb Function name: aFixedMemoryLeak() Before memcpy a = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa b = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb c = cccccccccccccccccccccccccccccc After memcpy a = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb b = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb c = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa Original value of c is now overwritten Source string is Hello there length 11 Copy of source string is Hello there length 11 Now calling getPersonDetails() Person just created is: Johnny Doe Person name = Johnny Doe