Is LTO allowed to remove unused global object if there is code in a different translation unit relying on side effects of its construction?

后端 未结 3 1047
鱼传尺愫
鱼传尺愫 2021-01-14 22:38

First, just to avoid XY problem: this issue comes from https://github.com/cnjinhao/nana/issues/445#issuecomment-502080177. The library code should probably not do such thing

3条回答
  •  北荒
    北荒 (楼主)
    2021-01-14 23:30

    Don't have global static variables.

    The order of initialization is undefined (in the general case).

    Put static objects inside funcations as static objects then you can gurantee they are created before use.

    namespace lib
    {
    static int* default_font_id;
    
    int get_default_font_id()
    {
        return *default_font_id;
    }
    
    void initialize_font()
    {
        default_font_id = new int(1);
    }
    }
    

    // Change this too:

    namespace lib
    {
    
    int get_default_font_id()
    {
         // This new is guaranteed to only ever be called once.
         static std::unique_ptr default_font_id = new int(1);
    
         return *default_font_id;
    }
    
    void initialize_font()
    {
        // Don't need this ever.
    }
    }
    

提交回复
热议问题