👨🏭Helper function
C and C++ both have many helper functions which make it easier to work with memory, here are main ones explained:
new and delete operators:
new
: Allocates memory for a single objectdelete
: Deallocates memory for a single objectnew[]
: Allocates memory for an array of objectsdelete[]
: Deallocates memory for an array of objects
C-style memory management functions (from <cstdlib>):
malloc()
: Allocates a block of uninitialized memorycalloc()
: Allocates a block of zero-initialized memorymemset()
: 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 blockfree()
: Deallocates a block of memory previously allocated by malloc, calloc, or realloc
Smart Pointers (from <memory>):
std::unique_ptr
: For exclusive ownership of dynamically allocated memorystd::shared_ptr
: For shared ownership of dynamically allocated memorystd::weak_ptr
: A weak reference to an object managed by std::shared_ptr
Allocator class (from <memory>):
std::allocator
: The default allocator used by standard containers
Other memory-related functions (from <memory>):
std::addressof()
: Obtains the actual address of an objectstd::align()
: Aligns pointer to the specified alignmentstd::uninitialized_copy()
: Copies a range of objects to uninitialized memorystd::uninitialized_fill()
: Fills a range of uninitialized memory with a valuestd::uninitialized_move()
: Moves a range of objects to uninitialized memorystd::destroy()
: Destroys objects in a range
C++17 additions:
std::launder()
: Helps deal with object lifetime issues in certain scenarios
C++20 additions:
std::make_unique_for_overwrite()
: Creates a unique_ptr without value-initializing its contentsstd::make_shared_for_overwrite()
: Creates a shared_ptr without value-initializing its contents
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