C++ Logo

std-proposals

Advanced search

[std-proposals] consteval variables

From: Mital Ashok <mital_at_[hidden]>
Date: Wed, 31 Jul 2024 09:46:11 +0100
Hi,

I was thinking about writing a proposal for consteval variables.

They would have similar restrictions as consteval functions: It can
only be ODR-used in an immediate function context (and ODR-use would
be immediate escalating).

One advantage is they will not have an address at runtime. So no more
symbols for a single padding byte for the std::ranges niebloids or
other `static constexpr` variables.

The main feature is that the destructor of a consteval variable is
called (at the end of the translation unit or something), allowing a
transient allocation, e.g., `consteval std::vector<int> x = { 1, 2, 3
};`.
`int* p = x.data()` would still be ill-formed because `x.data()` as a
constant expression points to a transient allocation (which is not a
permitted result of a constant expression), but `int y = x[0];` would
be allowed. This would be an alternate solution to the ones proposed
in P2670R1.

This can already be kind-of implemented with a consteval function, but
you have to call it every time and compilers are not always good at
caching consteval function calls (See also:
<https://github.com/llvm/llvm-project/issues/61425>). Plus, there
would only be a single object, so:

  consteval std::vector<int> var = {1, 2, 3};
  consteval std::vector<int> fn() { return {1, 2, 3}; }
  static_assert(var.data() == var.data());
  static_assert(fn().data() != fn().data());

Would there be any interest in this? Or any related thoughts?

Thanks,
Mital

Received on 2024-07-31 08:46:49