Memory and pointers · Lesson 13 of 21
Smart pointers and RAII
unique_ptr and shared_ptr, and the idea that makes C++ safe.
RAII (Resource Acquisition Is Initialization) is C++'s most important idea: tie every resource (memory, a file, a connection, a lock) to a stack object. The object acquires it in its constructor and releases it in its destructor. Since the destructor runs automatically when the object leaves scope, the resource is never forgotten, even when an exception is thrown.
#include <iostream>
#include <memory>
#include <string>
struct Course {
std::string title;
explicit Course(std::string t) : title(std::move(t)) { std::cout << "open " << title << "\n"; }
~Course() { std::cout << "close " << title << "\n"; }
};
int main() {
{
std::unique_ptr<Course> c = std::make_unique<Course>("C++");
std::cout << "studying " << c->title << "\n";
} // c leaves scope here: the Course is deleted automatically
std::cout << "after the block\n";
return 0;
}unique_ptr means one owner: it can't be copied, but ownership can be moved with std::move. shared_ptr means many owners: it counts holders and frees the object when the last one lets go.
#include <iostream>
#include <memory>
#include <vector>
int main() {
auto a = std::make_unique<int>(5);
auto b = std::move(a); // ownership moves to b
std::cout << (a == nullptr) << " " << *b << "\n";
auto shared = std::make_shared<int>(7);
std::vector<std::shared_ptr<int>> owners = {shared, shared};
std::cout << "owners: " << shared.use_count() << "\n";
owners.clear();
std::cout << "owners: " << shared.use_count() << "\n";
return 0;
}make_shared: count 1
two copies in the vector: count 3
clear(): count 1
shared leaves scope: count 0, so it's freed
What's the output?
#include <iostream>
#include <memory>
struct T {
int id;
T(int i) : id(i) {}
~T() { std::cout << "bye" << id << " "; }
};
int main() {
auto a = std::make_unique<T>(1);
{
auto b = std::make_unique<T>(2);
}
std::cout << "end ";
}What will this code print?
Exercise
Create a std::unique_ptr<std::vector<int>> holding {3, 1, 4} with std::make_unique, add 1 and 5 with push_back through ->, and print its size.
Expected output: 5
#include <iostream>
#include <memory>
#include <vector>
int main() {
return 0;
}Learn more from
Played 0 of 2 games
Sign in to save your progress and earn XP.