RAII & Smart PointersBeginner
1Question 1 of 1
cppWhat is RAII (Resource Acquisition Is Initialization) and how do Smart Pointers manage memory in modern C++?
Explanation & Concept
RAII is a core C++ idiom: resources (heap memory, file handles, mutex locks) are acquired in a constructor and automatically released in the destructor.
Modern C++ eliminates manual `new` and `delete` using standard smart pointers: • `std::unique_ptr`: Sole, exclusive ownership of a heap resource (cannot be copied, only moved). • `std::shared_ptr`: Reference-counted ownership of a heap resource. • `std::weak_ptr`: Non-owning reference to break circular dependencies.
Code Example
cpp
#include <iostream>
#include <memory>
class Resource {
public:
Resource() { std::cout << "Resource acquired\n"; }
~Resource() { std::cout << "Resource destroyed automatically\n"; }
void work() { std::cout << "Working...\n"; }
};
int main() {
{
// Allocated on heap, managed by unique_ptr
auto res = std::make_unique<Resource>();
res->work();
} // Out of scope: destructor called automatically here! Zero leaks!
return 0;
}How It Works & Key Takeaways
Even if an exception is thrown inside the scope, stack unwinding guarantees that destructors run and resources are freed without leaks.
Mock Test · 1 Questions · Optional
Ready for Templates?
Take a quick test to evaluate yourself, or move straight to the next module.
Beginner3 questions