Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct
For a noob like me, can you explain the use of int for QVector size/length?
In Fo last edited by
I am only developing in C++ for some 27 years, and being new to Qt, I am quite surprised that QVector.length() is a signed int. What is your motivation for using a signed integer?
Hi and welcome to devnet,
Negative values have a meaning.
For more details about that subject, I invite you to take a look the development mailing list where it has been discussed recently.
In Fo last edited by In Fo
I presume that functions like QImage.setPixel(int, int) or QRgb(int, int, int) also use negatives for special processing then? It is just surprising that many traditional uses of unsigned imply that there my be negatives, and this is all over Qt, too many to provide as examples here.
Not necessarily, you asked for the container case, it cannot be generalized for everything.
-1 is usually used to create objects that are in a known invalid state if these object shall contain only positive value for example. QSize is an example of such a use.
The topic of should
size_tbe signed or unsigned has been a holy war for as long as I can remember and Qt and the standard basically fell on the opposite sides of the argument, though I've seen a lot of standardization committee members saying that it was a mistake to make it unsigned, but it's too late.
Now, whether you agree or not is irrelevant at this point. I don't see either Qt or the standard changing sides. Too much stuff would just break at this point.
The basic argument against signed size is "how can size be negative?". While logical, the years have shown that size types are used not only for size, but also for size difference and unsigned types lead to all sorts of nasty bugs like
size-1when a container is empty. Obviously that's a bug that should be fixed, but just real life shows that this happens in so many places and in not so obvious circumstances that it's just less error prone to have it signed.
Whether a negative number should be used as a meaningful values is another holy war. Some say exceptions should be used, some say a ref argument and a return value indicating success/failure, others claim std::optional is the solution for everything...
Those things are basically opinions.
In Fo last edited by
Yes, we've moved on from the containers to other functions. Are there situations where negatives have a special meaning in them, like in those that I provided examples for?
Obviously that's a bug that should be fixed, but just real life shows that this happens in so many places and in not so obvious circumstances that it's just less error prone to have it signed.
The standard pretty much conceded on that point by introducing