Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ and QT4.5 - is passing a const int& overkill? Does pass by reference helps in signals/slots?

Two questions rolled into one here...

I have a number of functions which are called multiple times per frame for a real-time video processing application. Taking advice about const and pass by reference, the functions have a signature somewhat like this

void processSomething(const int& value);

As I keep typing the few extra characters, I am wondering if this is overkill.

Second question, well, on the subject of pass by reference, within the slots/signals mechanism of QT, does pass by reference helps to prevent copying of objects as in a normal function call?

like image 482
Extrakun Avatar asked Aug 26 '09 08:08

Extrakun


1 Answers

Yes, this is overkill and will actually result in slower code than if you passed the int by value. An int is four bytes; a reference (essentially a memory address) is either also four bytes (on a 32-bit machine) or eight bytes (on a 64-bit machine). So you may actually need to pass more information to the function -- and additionally, you have the overhead of dereferencing that reference.

If you're passing something bigger than an int, however, it's more efficient to use a const reference, because you can pass just four or eight bytes instead of having to copy the whole object.

Edit Regarding Qt: Yes, if the slot takes a const reference to an object, then the reason for that is to save the overhead of copying the object.

like image 105
Martin B Avatar answered Sep 20 '22 06:09

Martin B