Dynamic Memory and Smart Pointers
Dynamic memory is created while the program is running. Modern C++ normally manages ownership with smart pointers instead of direct calls to new and delete.
Why Smart Pointers Matter
A smart pointer releases its object automatically when ownership ends. This reduces memory leaks and makes ownership clearer.
unique_ptr and make_unique
Smart pointer example
#include <iostream>
#include <memory>
#include <string>
using namespace std;
class Student
{
public:
string name;
explicit Student(string studentName)
: name(studentName)
{
}
};
int main()
{
unique_ptr<Student> student = make_unique<Student>("Alice");
cout << student->name << endl;
return 0;
}Understanding Ownership
- A
unique_ptrhas one owner. - Use
make_unique()to create the object. - Use
->to access members through the pointer. - The object is destroyed automatically when the smart pointer leaves scope.
Modern C++ guidance
For most beginner and application-level code, prefer standard containers and smart pointers over raw dynamic allocation.
Practice task
Create a unique_ptr that owns a Product object and display its name and price.
Lesson Summary
Manage dynamically created objects safely with unique_ptr and make_unique.