Solved Signal/slot and const parameters
-
@KroMignon
I'm not a C++ Guru, but I would say it is a good idea. If it's aconst &
then make it so (like you show, in both signal & slot). Qt in-built signals/slots do this (I don't know know if they do it everywhere, but they do do it). -
@KroMignon said in Signal/slot and const parameters:
When I declare a signal or a slots in my class, is it a good or stupid idea to add "const &" to parameters?
Good idea for signals as well as slots :)
(As long as the parameter has a size > sizeof(pointer)
-
@aha_1980 Thanks for your attention, but does I need to have "const &" for each Signal and Slot or does it only made sense for Slots?
And when I use
QMetaObject::invokeMethod()
, do I need to add "const &" inQ_ARG()
? -
It makes sense to add it in the declaration of both signals and slots. Qt will take care automatically of the lifecycle for arguments passed across threads.
SGNAL()
andSLOT()
all support both the versions with and withoutconst &
but it's faster at execution if you leave it out.So following your example:
void newMessage(const MessageInfo& message);
void onNewMessage(const MessageInfo& message);
connect(collector,SIGNAL(newMessage(MessageInfo)),listener,SLOT(onNewMessage(MessageInfo));
-
I also recommend declaring signals as const:
signals: void newMessage(const MessageInfo& message) const;
Every signal can be const (always), it may help compiler optimize stuff, and it allows you to emit a signal also from
const
methods. So you can win (a small bit) and don't loose anything. -
@sierdzio said in Signal/slot and const parameters:
I also recommend declaring signals as const
Mixed feeling about this. Qt internally will
const_cast
the sender if the signal isconst
so it might be misleading to the user to assume the method is const. The moc of your signal will look something like this:// SIGNAL 0 void DataCollrecor::newMessage(const MessageInfo & _t1)const { void *_a[] = { Q_NULLPTR, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) }; QMetaObject::activate(const_cast< DataCollrecor *>(this), &staticMetaObject, 0, _a); }
-
Thanks @sierdzio and @VRonin for your inputs, just complete my questioning, what will happen if signal/slot parameter don't match with "const &".
To continue with my basic example:- void newMessage(MessageInfo message);
- void onNewMessage(const MessageInfo& message);
or:
- void newMessage(const MessageInfo& message);
- void onNewMessage(MessageInfo message);
Is there a risk to loose data or getting software crashes?
-
@KroMignon said in Signal/slot and const parameters:
what will happen if signal/slot parameter don't match with "const &".
You are calling a useless copy constructor
Is there a risk to loose data or getting software crashes?
No, just an efficiency issue
-
-
@VRonin said in Signal/slot and const parameters:
Mixed feeling about this. Qt internally will const_cast the sender if the signal is const
:O I had no idea.