cpp_weekly
cpp_weekly copied to clipboard
How constexpr vector works in C++20
This is effectively what you have to do to do constexpr vector-like things. Placement new is not yet constexpr (C++26) and you cannot change pointer types at compile time until C++26 too.
So you cannot just "new" a bunch of bytes then expect to use them.
#include <string>
constexpr void f()
{
std::allocator<std::string> allocator;
auto *ptr = allocator.allocate(10);
std::construct_at(ptr, "Hello a long string");
std::construct_at(ptr + 1, "World");
std::destroy_at(ptr);
std::destroy_at(ptr+1);
allocator.deallocate(ptr, 10);
}
int main()
{
[] consteval { f(); }();
}