PDA

View Full Version : A more extended explanation for Q_UNUSED macro ?



tonnot
16th March 2011, 14:35
I dont understand the benefits of use it.
Can anybody explain it ?
Thanks

high_flyer
16th March 2011, 15:13
As the docs say:


Q_UNUSED ( name )

Indicates to the compiler that the parameter with the specified name is not used in the body of a function. This can be used to suppress compiler warnings while allowing functions to be defined with meaningful parameter names in their signatures.

tonnot
16th March 2011, 17:10
I already read the docs.
I dont understand what means :

.... with the specified name is not used in the body of a function ...

Thanks

squidge
16th March 2011, 17:50
If you have a method which takes two variables and you don't use one of them, then one of them is unused, yes? So you can use Q_UNUSED macro to tell the compiler that you didn't forget about it and you know it's unused, otherwise you could receive warning message.



int foo::bar(int a1, int a2, int a3)
{
Q_UNUSED(a3);
int r = a1 + a2;
return r;
}

Octal
16th March 2011, 17:56
for example :



bool Foo::removeRow(const QModelIndex &index, const QModelIndex &parent)
{
Q_UNUSED(parent);
list.removeAt(index.row());
return true;
}


The parent parameter is not used inside the body of the function, which could result in a warning. Q_UNUSED here helps avoiding this warning, explicitly telling the compiler you're not using the concerned parameter.

I didn't really check in the Qt sources, but I guess the Q_UNUSED macro is defined like this :



#define Q_UNUSED(arg) (void)arg;

tonnot
16th March 2011, 17:56
Ok, I understand !!!
( And I have delete what I had written.)
Thanks

Quasar
22nd May 2012, 23:34
But i can't understand WHY to pass unusued parameter?

ChrisW67
23rd May 2012, 03:47
You might get unused parameters when you implement a slot to match a signal, or implement a virtual function, but do not need everything that is passed in order to complete your processing. For example, you might want to know when the "textChanged(QString)" signal is emitted from a QLineEdit but not care what the text changed to:


void handleTextChanged(const QString &text)
{
Q_UNUSED(text);
// make obnoxious noise
}


You can also suppress the warnings like this:


void handleTextChanged(const QString & /*text*/ )
{
// make obnoxious noise
}