Given a class that defines an event and has a costly constructor (in my case, it computes a hashe of the event name so that I can later perform comparisons against an int instead of the event name string), I found that the way to go in order not to repeat the construction operation is to have a static const declaration, so it gets constructed the first time and reused again and again.
Let us say the constructor of the event class is this:
Event(const char *name);
And I have a function to send events like this one:
send(const Event &e);
I would like to send an event in a way similar to the following:
// For instance
send("myevent");
...
// Or even
send(Event("myevent"));
But that of course calls the Event constructor every time the event is send. The first solution I came up with is to declare a static const before the call:
static const Event myevent("myevent");
send(myevent);
That's not too bad, but in order to convert this construct into a one-line statement I can use the preprocessor:
// Preprocessor macro
#define SEND(event_name) \
{ static const Event myevent(event_name); \
send(myevent); }
...
// And then later
SEND("myevent");
Although I would prefer not using the preprocessor if possible. That could be done if I could tell the compiler I want an rvalue like the Event instance in this case to be static const, which I don't know if possible... does it make sense?
Thanks!
Aucun commentaire:
Enregistrer un commentaire