constinit 说明符 (C++20 起)
来自cppreference.com
解释
constinit 说明符声明拥有静态或线程存储期的变量。
| (C++26 起) |
如果变量以 constinit 声明,那么它的初始化声明必须应用 constinit。如果以 constinit 声明的变量拥有动态初始化(即使作为静态初始化执行),那么程序非良构。
如果在初始化声明点没有可达的 constinit 声明,那么程序非良构,不需要诊断。
constinit 不能和 constexpr 一同使用。当声明的变量为引用时,constinit 等价于 constexpr。当声明的变量为对象时,constexpr 强制对象必须拥有静态初始化和常量析构,并使对象有 const 限定,然而 constinit 不强制常量析构和 const 限定。结果是拥有 constexpr 构造函数但没有 constexpr 析构函数的类型(例如 std::shared_ptr<T>)的对象可能可以用 constinit,但不能用 constexpr 声明。
const char* g() { return "动态初始化"; }
constexpr const char* f(bool p) { return p ? "常量初始化器" : g(); }
constinit const char* c = f(true); // OK
// constinit const char* d = f(false); // 错误
constinit 也能用于非初始化声明,以告知编译器 thread_local 变量已被初始化,以减少隐藏的防卫变量所致的开销。
extern thread_local constinit int x;
int f() { return x; } // 无需检查防卫变量
注解
| 功能特性测试宏 | 值 | 标准 | 功能特性 |
|---|---|---|---|
__cpp_constinit |