From a realtime thread, sometimes I need to issue notifications towards the message thread.
To avoid allocation of a new Message instance for every notification, is it ok if I allocate beforehand just one instance of the Message I want to send, and post() that same instance on the message queue whenever I need to send the notification?
That, of course, could happen multiple times during the lifetime of my program, and the doc for message says:
Always create a new instance of a Message object on the heap, as it will be deleted automatically after the message has been delivered.
… but the Message classes are reference counted anyway, so I thought to give it a try and it just works.
I have tested with this simple class:
struct DebugMessage : public juce::Message
{
DebugMessage (const juce::String& t) : text (t)
{
DBG ("DebugMessage (\"" + text + "\")");
}
~DebugMessage () override
{
DBG ("~DebugMessage (\"" + text + "\")");
}
void messageCallback () override
{
DBG ("messageCallback (\"" + text + "\")");
}
juce::String text;
};
Of which I create two instances as members of a MainComponent in a test application, which I keep track of in reference counted pointers:
juce::Message::Ptr msg1 {new DebugMessage ("msg1")};
juce::Message::Ptr msg2 {new DebugMessage ("msg2")};
At this point, I can post both messages several times:
msg1->post();
msg2->post();
msg1->post();
msg2->post();
And the outcome is exactly what I would have expected:
- The constructor for each message is called exactly once
- The callback for each message is called as many times I have posted the message, in the correct order
- The destructor for each message is also called exactly once, at program exit
Given the fact that it currently already works as expected, my question is: can this be relied upon?