Dynamic Memory and Smart Pointers
new allocates memory and delete frees it, but forgetting delete leaks memory. Smart pointers from <memory> free automatically: unique_ptr has one owner and shared_ptr counts owners. Use make_unique and make_shared.
Example
#include <iostream>
#include <memory>
using namespace std;
struct Box {
int value;
Box(int v) : value(v) { cout << "created " << v << endl; }
~Box() { cout << "destroyed " << value << endl; }
};
int main() {
{
auto b = make_unique<Box>(7);
cout << b->value << endl;
}
cout << "after scope" << endl;
}Result
created 7 7 destroyed 7 after scope
Exercise
Create a uniquely owned object.
auto p = <Box>(7);
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.