c++ - 如何防止 GCC 为静态成员生成守卫

标签 c++ gcc static g++ compiler-optimization

以下是一个有时会生成守卫有时不会生成的最小示例:

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

总结一下:
  • 在 A 类中没有 ctor,永远不会生成守卫
  • 使用 anaon-ns 也可以防止守卫
  • 制作静态成员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/

    相关文章:

    c# - 静态类的静态方法与非静态类的静态方法 (C#)

    java - Java中的List如何实现静态对非静态的引用?

    c++ - Octave - 访问 octave_value_list 中的值

    c++ - 如何在 "edit"按键上杀死 "Enter"控件的焦点

    C优化中断算法

    linux - 如何知道gcc安装的确切位置

    static - API : Top 100 twitter users in a country (rank by followers)

    c++ - 从 DirectX 11.2 应用程序打开或创建文件

    c++ - 使用 CStdioFile 写入字符串

    c++ - 嵌套模板和参数推导