Table of Contents
1. Memory management and smart pointers
Memory management in C++ can easily cause problems if the programmer doesn't take special care when using them. They can lose track of memory addresses, being unable to free that memory while the program runs (memory leak), you can accidentally try to free memory at an address that was already freed previously (double-free error), and once you factor in bringing in other developers to work with a system it can become even more likely for something to go wrong.
1.1. Making pointers smarter
We could make our own "smart pointers" by utilizing classes and their constructors/destructors. For example, let's say you make a simple class that wraps a pointer to use for a dynamic array:
class IntArray { public: IntArray( int size ); ~IntArray(); void Add( int newValue ); void Remove( int atIndex ); // etc private: int* ptr; int arraySize; };
We could make sure memory is allocated with the constructor, which is called automatically when a new IntArray object is created:
IntArray::IntArray( int size ) { ptr = new int[ size ]; arraySize = size; }
And that it's freed with the destructor, which is called automatically when the object is destroyed (such as going out of scope):
IntArray::~IntArray() { if ( ptr != nullptr ) // it's pointing to an address { delete [] ptr; } }
1.2. Smart pointers in C++11
In C++11 (from 2011) and on, new "Smart Pointer" types were added. These deal with the memory but wrap it inside of a class so that freeing memory can be done automatically as needed, thanks to the use of destructors. These smart pointers can be used in your program by including the memory library:
#include <memory>
2. Unique Pointer
With the unique_ptr, only that one pointer can "own" an object
allocated at some memory address. For instance, with a traditional
dynamic array, we could do allocate space, but there's nothing
stopping other pointers from pointing at it.
int* oldDynArr = new int[ 100 ]; int* otherPtr = &oldDynArr; // This might be bad! /* ... end of program ... */ delete [] oldDynArr; oldDynArr = nullptr; // Now otherPtr might be dereferenced, but the memory address is invalid now!
With a unique_ptr we can allocate that space and have it own that
location. Additionally, since it's a Smart Pointer, it will also
take care of the delete [] oldDynArr so we don't have to.
Documentation for unique_ptr:
https://cplusplus.com/reference/memory/unique_ptr/
2.1. Declaring a unique pointer
Declaring a unique pointer type looks like this:
unique_ptr<TYPE> NAME;
And you can then allocate memory later:
unique_ptr<int> intObj; intObj = unique_ptr<int>( new int ); const int ARRAY_SIZE = 20; unique_ptr<float[]> floatArr; floatArr = unique_ptr<float[]>( new float[ ARRAY_SIZE ] );
Or you can immediately allocate memory:
unique_ptr<TYPE> NAME = unique_ptr<TYPE>( INIT );
unique_ptr<int> intObj = unique_ptr<int>( new int ); const int ARRAY_SIZE = 20; unique_ptr<float[]> floatArr = unique_ptr<float[]>( new float[ ARRAY_SIZE ] );
Since this is modern C++, you can shorten this a bit by using auto
for the declaration, as it will figure out what data type it is
automatically based on its initialization:
auto intObj = unique_ptr<int>( new int ); const int ARRAY_SIZE = 20; auto floatArr = unique_ptr<float[]>( new float[ ARRAY_SIZE ] );
2.2. Using the unique pointer
Once the unique pointer is used we can use it like a normal pointer. If we allocated space for a single object, we can still dereference it to access the value:
auto singleObject = unique_ptr<int>( new int ); *singleObject = 100; cout << *singleObject << endl;
And if it's a dynamic array you can still access elements with the subscript operator:
const int SIZE = 10; auto arr = unique_ptr<int[]>( new int[SIZE] ); for ( int i = 0; i < SIZE; i++ ) { arr[i] = rand() % 100; cout << arr[i] << endl; }
And if it's an object, you still can access members with the arrow
operator ->:
#include <iostream> #include <memory> #include <string> using namespace std; class Item { public: Item( string newName ) { name = newName; } void SetName( string newName ) { name = newName; } void Display() { cout << "Item: " << name << endl; } private: string name; }; int main() { auto singleObject = unique_ptr<Item>( new Item( "Bob" ) ); singleObject->Display(); singleObject->SetName( "NotBob" ); singleObject->Display(); return 0; }
2.3. Moving ownership
In some cases you might want to move ownership over an object to another unique pointer, which you could use the move function for:
// Change ownership from the "original" place to the "newPointer". newPointer = move( original );
As an example if you were using a unique_ptr for a
dynamic array and needed to "resize" the array by making a bigger
array in a new memory space:
unique_ptr<int[]> biggerArray = unique_ptr<int[]>( new int[ size+10 ] ); // ... copy values over from originalArray ... // ... now we need to change ownership over the biggerArray space originalArray = move( biggerArray ); // Now the original array we were using owns the larger location space.
Review 1. What is the form of a unique_ptr declaration?
Review 2. What does the move function do?
3. Shared Pointer
In other cases, we may want to have multiple pointers that point to
the same object. With a shared pointer, it keeps an interal count
of how many pointers are active. When the last shared_ptr that owns
the spot is destroyed, then the internal pointer is finally freed.
Documentation for shared_ptr:
https://cplusplus.com/reference/memory/shared_ptr/
3.1. Declaring a shared pointer
Declaring a shared pointer looks like this:
// Declartion shared_ptr<TYPE> NAME; // Assignment NAME = shared_ptr<TYPE>( new TYPE( VALUE ) ); // Or declare and assign in one step shared_ptr<TYPE> NAME = shared_ptr<TYPE>( new TYPE( VALUE ) ); // Or you could use auto: auto NAME = shared_ptr<TYPE>( new TYPE( VALUE ) );
3.2. Using the shared pointer
We can use these pointers as normal, dereferencing them to assign or read values…:
auto studentA = shared_ptr<string>( new string( "???" ) ); *studentA = "Hikaru"; cout << "Student A: " << *studentA << endl;
Multiple pointers can point to the same place, and you can use the
use_count function to see how many pointers are shared to this object.
#include <iostream> #include <memory> #include <string> using namespace std; int main() { auto studentA = shared_ptr<string>( new string( "Hikaru" ) ); auto studentB = shared_ptr<string>( new string( "Umi" ) ); auto studentC = shared_ptr<string>( new string( "Fuu" ) ); auto bestStudent = studentC; auto studentNeedsGlasses = studentC; auto fencingAward = studentB; cout << "Student A: " << *studentA << ", use count: " << studentA.use_count() << endl; cout << "Student B: " << *studentB << ", use count: " << studentB.use_count() << endl; cout << "Student C: " << *studentC << ", use count: " << studentC.use_count() << endl; return 0; }
Review 3. What is the form of a shared_ptr declaration?
Review 4. What does the use_count function do?