How to share global constants with minimum overhead at runtime?

后端 未结 5 552
[愿得一人]
[愿得一人] 2021-01-19 05:21

I am using C++11. I am not allowed to use external libraries like boost etc. I must use STL only.

I have a number of events, which must be identified as string const

5条回答
  •  失恋的感觉
    2021-01-19 06:07

    In light of the fact that you're stuck with C++11, I think my suggestion from here still stands:

    #ifndef INCLUDED_EVENT_NAMES
    #define INCLUDED_EVENT_NAMES
    
    #pragma once
    
    namespace event_names
    {
        constexpr auto& event_1 = "event_1";
        constexpr auto& event_2 = "event_2";
    }
    
    #endif
    

    Defining named references to string literal objects is very simple, does not require any additional libraries, is guaranteed to not introduce any unnecessary objects, won't require any additional memory over the storage for the statically-allocated string literal objects that you'd need anyways, and will not have any runtime overhead.

    If you could use C++17, I'd suggest to go with the std::string_view approach, but in C++11, I think the above is most-likely a good compromise for your application.

提交回复
热议问题