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

  1. allocateMemory() is not…

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store