How to share global constants with minimum overhead at runtime?

后端 未结 5 591
[愿得一人]
[愿得一人] 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:09

    The easiest way would be to use a char const* constant, as it's way more optimizable and don't use dynamic allocations.

    Also you can use std::string_view in the postEvent function, avoiding dynamic allocations. This step is optional. If you cannot have string views and still want to avoid dynamic allocations, then refer to your implementation's SSO max capacity and keep event names below that size.

    Also consider that nonstd::string_view can be shipped as a C++11 library and most likely the abstraction you need. Library such as cpp17_headers and string-view-lite exist solely for that purpose.

    It look like this:

    constexpr auto event_name1 = "event_name1";
    

    In a class as a static member it works the same way:

    struct Type {
        static constexpr auto event_name1 = "event_name1";
    };
    

    This will at most take space in the read-only static data of your executable.

提交回复
热议问题