以下是一个有时会生成守卫有时不会生成的最小示例:
struct A {
inline A(int v = 0) {} // without ctors, guards are omitted
int m1() const {
return m;
}
private:
int m = 0;
};
//namespace { // without anon-ns guards are generated
template<typename T>
struct X {
static int foo() {
// static T m; // even as local-static and -fno-threadsafe-statics, guards are generated
return m.m1();
}
inline static T m; // comment this and uncomment above to try as local-static
};
//}
int main() {
return X<A>::foo();
}
总结一下:
m
foo()
中的静态局部变量仍然生成 guard (使用 -fno-threadsafe-statics
)(注释/取消注释上面示例中的相应行)那么,如何避免在案例类
A
中生成守卫有 ctor 并且无法使用 anon-ns 吗?
最佳答案
抑制守卫的关键特性是 constinit 和 constexpr ctors:
#include <cstdint>
struct A {
inline constexpr A(uint8_t v) : m{v} {} // without constexpr it should not compile, but does anymay
auto m1() const {
return m;
}
private:
uint8_t m{0};
};
template<typename T>
struct X {
static auto foo() {
return m.m1();
}
constinit inline static T m{2}; // requires constexpr ctor
};
int main() {
return X<A>::foo();
}
与
constinit
初始化必须在编译时执行,因此不需要生成 guard 。这需要一个 constexpr
医生。在上面的例子中,可以在没有 constexpr
的情况下声明 ctor(至少对于 gcc)。 ,但这可能是一个未决的错误。
关于c++ - 如何防止 GCC 为静态成员生成守卫,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58289965/