Memory Allocation in C++

C++ provides two ways to allocate and free unconstructed, raw memory:

1. The allocator class, which provides type-aware memory allocation. This class supports an abstract interface to allocating memory and subsequently using that memory to hold objects.
2. The library operator new and operator delete functions, which allocated and free raw, untyped memory of a requested size.

C++ also provides various ways to construct and destroy objects in raw memory:



1. The allocator class defines members named construct and destroy, which operate as their names suggest. The construct member initializes objects in unconstructed memory; the destroy member runs the appropriate destructor on objects.
The allocator class is a template that provides typed memory allocation and object construction and destruction.
2. The placement new expression takes a pointer to unconstructed memory and initializes an object or an array in that space.
3. We can directly call an object's destructor to destroy the object. Running the destructor does not free the memory in which the object resides.
4. The algorithms uninitialized _fill and uninitialized_copy execute like the fill and copy algorithms except that they construct objects in their destination rather than assigning to them.
Modern C++ programs ordinarily ought to use the allocator class to allocate memory. It is safer and more flexible. However, when constructing objects, the placement new expression is more flexible than the allocator::construct member. There are some cases where placement new must be used.

No comments: