In Modern C++ (C++11 and beyond), manual memory management with new and delete is considered an anti-pattern. Instead, modern software relies on Smart Pointers defined in the <memory> header to automate resource cleanup via RAII.
std::unique_ptr<T> (Exclusive Ownership)#include <iostream>
#include <memory>
class Sensor {
public:
Sensor() { std::cout << "Sensor initialized\n"; }
~Sensor() { std::cout << "Sensor destroyed automatically!\n"; }
void readData() { std::cout << "Reading telemetry...\n"; }
};
int main() {
{
// Safe creation: Zero raw new/delete
auto s = std::make_unique<Sensor>();
s->readData();
} // Exiting block: Destructor automatically called here!
return 0;
}
std::shared_ptr<T> and std::weak_ptr<T>#include <iostream>
#include <memory>
int main() {
// Shared ownership with reference counting
auto p1 = std::make_shared<int>(500);
std::cout << "Initial count: " << p1.use_count() << "\n"; // 1
{
auto p2 = p1; // Copy increments reference count
std::cout << "Inside scope count: " << p1.use_count() << "\n"; // 2
} // p2 destroyed, count decrements back to 1
std::cout << "Outside scope count: " << p1.use_count() << "\n"; // 1
return 0;
}
Boost your C++ proficiency by studying these closely connected core modules:
Understanding why raw new/delete is dangerous.
How smart pointers wrap heap memory into stack scope.
Transferring unique_ptr ownership with std::move.