Smart pointers are useful in the new C++ standard. Here’s a short post detailing why do we use std::unique pointer and some caveats.
- unique_ptr vs raw pointer
- Programmer is responsible for explicitly freeing raw pointers and keep tracking of the ownership. This poses a big problem when the C++ program gets big and it’s hard to figure out the life time of a heap allocated object, leading to memory leaks.
- with unique_ptr, the heap-allocated object is deallocated when the pointer goes out of scope. There can only be one owner for the unique pointer.
For example
#include <memory>
#include <iostream>
using namespace std;
struct Car{
Car(string make): make_(make){}
~Car(){cout << "Sold";}
string make_;
};
int main(){
auto p = make_unique<Car>("toyota");
return 0;
}
If you run the above code, it will show “Sold” even though there’s no explicit free / delete on p. The pointer p goes out of scope after main has finished and the destructor is automatically invoked.
There can only be one unique pointer that owns the object on heap. As a result, you cannot make a copy of a unique pointer. However, you can transfer the ownership of the object with std::move
auto q = make_unique<int>();
auto p = q; // Error the object belongs to q and cannot be shared.
p = move(q); // OK, p now owns the object
Other options to consider
- if you can allocate on heap, that is the best. In the example above, just do Car p (“toyota”);
- you can also use std::optional.
Reference posts