RAII in C++
Sometimes at some part of the program, we need to allocate some memory and later free it.
template <typename T, std::size_t N>
T* allocateMemory()
{
return new T[N];
}template <typename T>
void freeMemory(T *p)
{
delete[] p;
}int main()
{
int *p = allocateMemory<int, 10>();
// use p
freeMemory(p);
return 0;
}
Disaster can happen when
- allocateMemory() is not called at all. Then the program will crash.
- freeMemory() is not called at all. There will be memory leak.
- freeMemory() is called twice from two different control paths or threads. It will cause double deletion and might crash.
This is a problem in C++, because resource management is developer’s responsibility. RAII or Resource Acquisition is Initialization is a pattern which fixes this problem.
In RAII
- Resource is a class invariant.
- Resource acquisition(memory allocation, file opening, acquiring mutex , database connection) is done when lifetime of the object begins. In C++11, lifetime of object begins after construction.
- Resource is available throughout the object lifetime.
- Resource is released when lifetime of the object object ends.