Smart Pointers
In the Dynamic Memory lesson, every new needed a matching delete, and a forgotten delete was a memory leak. In the Constructors lesson, you saw that a destructor runs by itself when an object is removed. Modern C++ puts these two ideas together. An object owns some memory, and its destructor gives that memory back. This idea is called RAII (Resource Acquisition Is Initialization). The name is long, but the rule is short: get the memory when the object is created, and free it in the destructor.
A vector already works this way. For a single object on the heap, C++ has smart pointers. The most common one is unique_ptr. To use it, add #include <memory>:
#include <iostream>
#include <memory>
#include <string>
using namespace std;
class Pet {
public:
string name;
Pet(string n) {
name = n;
cout << name << " arrives" << "\n";
}
~Pet() {
cout << name << " leaves" << "\n";
}
};
int main() {
{
unique_ptr<Pet> p = make_unique<Pet>("Rex");
cout << p->name << " is here" << "\n";
}
cout << "The block is over" << "\n";
return 0;
}
Output:
Rex arrives
Rex is here
Rex leaves
The block is over
make_unique<Pet>("Rex") creates a Pet on the heap, like new Pet("Rex"). It returns a unique_ptr<Pet> that owns the pet. You use -> with it, just like with a normal pointer.
The extra { } in main make a block. Rex leaves is printed at the end of that block, before the last line. When the block ended, p was removed, and it deleted the pet. There is no delete anywhere in the code.
Only one owner
"Unique" means that only one unique_ptr can own the object. Copying it does not compile:
#include <iostream>
#include <memory>
#include <string>
using namespace std;
class Pet {
public:
string name;
Pet(string n) {
name = n;
}
};
int main() {
unique_ptr<Pet> p = make_unique<Pet>("Rex");
unique_ptr<Pet> q = p;
return 0;
}
Output:
main.cpp: In function ‘int main()’:
main.cpp:17:25: error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = Pet; _Dp = std::default_delete<Pet>]’
The message is long, but "use of deleted function" is the important part. Copying is switched off on purpose. If two pointers owned the same pet, both would delete it, and deleting twice is a bug.
To hand the object to another unique_ptr, use move. After that, the old pointer is empty:
unique_ptr<int> a = make_unique<int>(5);
unique_ptr<int> b = move(a);
cout << *b << "\n";
cout << (a == nullptr) << "\n";
Output:
5
1
b now owns the 5. a == nullptr is true, so the second line prints 1.
A vector of shapes
Smart pointers work well with polymorphism. A vector of unique_ptr<Shape> can hold rectangles and squares, and it owns all of them:
#include <iostream>
#include <memory>
#include <vector>
using namespace std;
class Shape {
public:
virtual int area() = 0;
virtual ~Shape() {
cout << "Shape deleted" << "\n";
}
};
class Rectangle : public Shape {
public:
int width, height;
Rectangle(int w, int h) {
width = w;
height = h;
}
int area() override {
return width * height;
}
};
class Square : public Shape {
public:
int side;
Square(int s) {
side = s;
}
int area() override {
return side * side;
}
};
int main() {
vector<unique_ptr<Shape>> shapes;
shapes.push_back(make_unique<Rectangle>(4, 5));
shapes.push_back(make_unique<Square>(3));
for (int i = 0; i < shapes.size(); i++) {
cout << shapes[i]->area() << "\n";
}
return 0;
}
Output:
20
9
Shape deleted
Shape deleted
make_unique<Square>(3) gives a unique_ptr<Square>. It can go into the vector of unique_ptr<Shape>, because a square is a shape. shapes[i]->area() calls the right area, and when main ends, the vector deletes both shapes. This is why Shape has the virtual destructor from the last lesson.
shared_ptr
Sometimes several parts of a program must share one object. For that, C++ has shared_ptr. It can be copied, and use_count() tells you how many owners there are:
shared_ptr<int> first = make_shared<int>(7);
shared_ptr<int> second = first;
cout << first.use_count() << "\n";
Output:
2
The object is deleted when its last owner is gone. Use unique_ptr unless you really need more than one owner.
In the exercise, keep shapes in a vector of unique_ptr, and create each one with make_unique.