Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to share global constants with minimum overhead at runtime?

Tags:

c++

c++11

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 constants. I am not allowed to use enums or ints or any other data type. For example:

"event_name1"

"event_name2"

"some_other_event_name3"

"a_different_event_name12"

Then I have some classes which need to use these strings, but don't know the other classes exist (they don't have anything to do with each other).

class Panel{

    void postEvent(){
        SomeSingleton::postEvent("event_name");
    }
}

Another class::

class SomeClass{

    SomeClass(){
        SomeSingleton::listenForEvent("event_name");
    }

    void receiveEvent(){
         //This function is triggered when "event_name" occurs.
         //Do stuff
    }
}

All these events are constants, and are used to identify things that are happening.

Here is what I have tried:

How to store string constants that will be accessed by a number of different classes?

Some of the persons there suggested I provide specific details of how to solve a concrete problem, so I have created this new question.

How can I store the strings in a common file, so that all the other classes that use these strings can refer to the same file?

  • I do not want to waste memory or leak memory during my app's lifetime (it is a mobile app)
  • compilation times are not a big deal to me, since the project isn't so big
  • there are expected to be maybe 50 different events.
  • It seems it would be more maintainable to keep all the strings in one file, and edit only this file as and when things change.
  • Any class can listen for any event, at any time, and I won't know prior to compilation
like image 703
Rahul Iyer Avatar asked Dec 01 '22 09:12

Rahul Iyer


1 Answers

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.

like image 129
Guillaume Racicot Avatar answered Dec 04 '22 02:12

Guillaume Racicot