RAII in C++
RAII is one of the patterns in C++ to manage resources.
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…