- Example
In this lesson, we'll see a few examples of memory allocation and deallocation in C++.
We'll cover the following
RAII #
RAII stands for Resource Acquisition Is Initialization. Probably the most important idiom in C++ says that a resource should be acquired in the constructor of the object and released in the destructor of the object. The key is that the destructor will automatically be called if the object goes out of scope.
Is it not totally deterministic? In Java or Python (__del__
), we have a destructor but not the guarantee. Therefore, if we use the destructor to release a critical resource like a lock, it can end disastrously. But in C++, we are safe.
See the example below:
Get hands-on with 1400+ tech skills courses.