std::alloca...::construct(3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

πŸ’– std::allocator_traits::construct πŸ’–

ok so real talk, this page is from the C++ Standard Library manual and today's main character is std::allocator_traits::construct. we're getting into allocator lore bestie, buckle up πŸŽ€


✨ NAME ✨

std::allocator_traits::construct β€” std::allocator_traits::construct

(yes it says the same thing twice, that's just how manpages are, it's giving mirror selfie πŸ’…)

✨ SYNOPSIS ✨

Defined in header <memory> β€” don't forget it, iykyk.

template< class T, class... Args >
(since C++11)
static void construct( Alloc& a, T* p, Args&&... args );
(until C++20)
template< class T, class... Args >
(since C++20)
static constexpr void construct( Alloc& a, T* p, Args&&... args );

✨ DESCRIPTION ✨

So check it: if possible, this thing constructs an object of type T in allocated, uninitialized storage that p points at, by calling a.construct(p, std::forward<Args>(args)...). iconic, no notes πŸ’…

But what if that's not possible? Like, say Alloc just… doesn't have a member function construct()? (rude of it, but ok πŸ™ˆ) Then it calls:

::new (static_cast<void*>(p)) T(std::forward<Args>(args)...)   (until C++20)
std::construct_at(p, std::forward<Args>(args)...)              (since C++20)

lowkey the fallback is the whole personality of this function, and honestly? we stan a resourceful queen πŸ‘‘

✨ PARAMETERS ✨

  • a β€” allocator to use for construction. she's the one making it happen.
  • p β€” pointer to the uninitialized storage on which a T object will be constructed. it's empty in there rn, that's literally the point 🫢
  • args... β€” the constructor arguments to pass to a.construct(), or to placement-new (until C++20), or to std::construct_at() (since C++20). ngl this one is doing double duty.

✨ RETURN VALUE ✨

(none) β€” she gives and gives and asks for nothing back πŸ’œ

✨ NOTES ✨

This function is used by the standard library containers when inserting, copying, or moving elements. so like every single time you push_back something? she was there. main character energy fr fr 🌟

And here's the tea β˜•: because this function provides the automatic fall back to placement new, the member function construct() has been an optional Allocator requirement since C++11. optional!! we love a low-pressure commitment ✨

✨ SEE ALSO ✨

  • operator new, operator new[] β€” allocation functions (function)
  • construct β€” constructs an object in allocated storage (until C++20) (public member function of std::allocator<T>)
  • construct_at β€” creates an object at a given address (C++20) (function template)

ok that's the whole page bestie, go construct something beautiful πŸ¦‹

shoutout to cppreference.com, the 2024.06.10 edition, and this page literally titled std::alloca...::construct(3) β€” yes the title got truncated, no we don't know why, and yes she still ate πŸ’…πŸ’–

πŸ“¦ where this page comes from