mercredi 3 avril 2019

How to share global constants with minimum overhead at runtime?

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

Aucun commentaire:

Enregistrer un commentaire