cpp_weekly icon indicating copy to clipboard operation
cpp_weekly copied to clipboard

How constexpr vector works in C++20

Open lefticus opened this issue 1 year ago • 0 comments

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(); }();
}

lefticus avatar Aug 07 '24 15:08 lefticus