👨‍🏭Helper function

C and C++ both have many helper functions which make it easier to work with memory, here are main ones explained:

  1. new and delete operators:

    • new: Allocates memory for a single object

    • delete: Deallocates memory for a single object

    • new[]: Allocates memory for an array of objects

    • delete[]: Deallocates memory for an array of objects

  2. C-style memory management functions (from <cstdlib>):

    • malloc(): Allocates a block of uninitialized memory

    • calloc(): Allocates a block of zero-initialized memory

    • memset(): Fills a block of memory with a specified value.

    • memcpy():Copies a block of memory from a source to a destination.

    • realloc(): Reallocates a previously allocated memory block

    • free(): Deallocates a block of memory previously allocated by malloc, calloc, or realloc

  3. Smart Pointers (from <memory>):

    • std::unique_ptr: For exclusive ownership of dynamically allocated memory

    • std::shared_ptr: For shared ownership of dynamically allocated memory

    • std::weak_ptr: A weak reference to an object managed by std::shared_ptr

  4. Allocator class (from <memory>):

    • std::allocator: The default allocator used by standard containers

  5. Other memory-related functions (from <memory>):

    • std::addressof(): Obtains the actual address of an object

    • std::align(): Aligns pointer to the specified alignment

    • std::uninitialized_copy(): Copies a range of objects to uninitialized memory

    • std::uninitialized_fill(): Fills a range of uninitialized memory with a value

    • std::uninitialized_move(): Moves a range of objects to uninitialized memory

    • std::destroy(): Destroys objects in a range

  6. C++17 additions:

    • std::launder(): Helps deal with object lifetime issues in certain scenarios

  7. C++20 additions:

    • std::make_unique_for_overwrite(): Creates a unique_ptr without value-initializing its contents

    • std::make_shared_for_overwrite(): Creates a shared_ptr without value-initializing its contents

  8. Placement new:

    • new (place_address) type: Constructs an object at a specific memory address

It's worth noting that in modern C++, direct use of low-level memory management functions like malloc() and free() is generally discouraged in favor of C++-style memory management (new/delete) or, even better, smart pointers and standard containers.

The smart pointers (unique_ptr, shared_ptr, weak_ptr) are particularly important as they help manage memory automatically and prevent common issues like memory leaks and dangling pointers.

Example:

Run it here.

Last updated