Reputation: 1205
In QString constructor and other functions QChar is passed by value, not by const ref: QString(QChar ch), however it's a class itself (class QChar), not a POD type. Why is it passed so?
Upvotes: 1
Views: 467
Reputation: 49299
According to some, it is because a QChar
is only 2 bytes, while a pointer is 4 or 8 bytes, so it is more efficient.
However, that isn't the full story. Modern machines take the same time to pass an architecture-native pointer as they take to pass a single byte, and in the end it all ends up on either a 32bit or 64bit register. And while it is true that this wasn't the case back in the days, and machines were much slower at passing large integers, their pointers were not 4 or 8 bytes long either. So at best, there is some gain if you say pass a byte by value instead of by reference on a 16bit machine from like 30 years ago.
Remember that the reference, if actually passed, is just a pointer, so the inefficiency has more to do with using an extra layer of indirection. Why pass a pointer just to go look for that object somewhere else in memory, when you can pass the object itself. At least theoretically.
In practice, compilers are very good at optimizing. Any type of function that could be called in a hot spot and could likely result in a tangible overhead would be trivial and thus would be inlined by the compiler instead of called, so no passing of parameter takes place. If you compare two trivial functions, one that passes by value and the other by reference, you will realize they result in exactly the same machine code.
So, it is passed by value because that's what makes sense theoretically, even if it doesn't matter in practice. And because you save a little on typing. You'd only need to pass by reference if you want to modify the object outside the function.
Upvotes: 0
Reputation: 2647
The QChar
class in Qt 5.6.2 has a single data member, an unsigned short
. Accordingly sizeof(QChar)
will be 2
on most platforms. That’s smaller than your usual pointer (normally 4 or 8 bytes).
So, you can treat a QChar
the same as you would any other fundamental type. In facts it is designed to work that way because it replaces char
in the Qt API.
The reason for passing by const ref is efficiency and makes perfect sense for large objects. Passing by value would mean an expensive copy in these circumstances. So you trade that for an added indirection (because under the hood a reference is usually implemented with a pointer) and are better of. For fundamental types that reasoning does not hold. Copying is cheap, so it’s more efficient to pass by value and avoid an added indirection.
Upvotes: 4