为何Qt的QFile::size()返回qint64而非quint64?
Great question! This is indeed a deliberate design choice in Qt, and there are a few key reasons behind it, along with some edge cases where negative values might come into play:
1. Interface Consistency Across QIODevice Subclasses
QIODevice is the base class for all I/O devices in Qt—not just files, but also network sockets, serial ports, pipes, and more. Many core I/O methods in QIODevice (like read(), write(), bytesAvailable()) return qint64:
- For operations like
read(), a return value of-1signals an error, while a non-negative value indicates the number of bytes successfully processed. - Using
qint64forsize()aligns with this consistent interface pattern, avoiding messy type conversions between signed and unsigned integers when working with different I/O devices.
2. Error Signaling (The Hidden Negative Scenario)
While file sizes are inherently non-negative, QFile::size() (and its parent class implementations) can return -1 in error scenarios that aren’t always emphasized in basic documentation:
- If the file is not opened (or fails to open when
size()attempts to access it), the method may return-1to indicate it couldn’t retrieve the size. - For non-file QIODevice subclasses (like network streams or pipes),
size()delegates tobytesAvailable()—though this method usually returns non-negative values, in rare error states it might return-1to signal a problem with the device.
3. Cross-Platform Compatibility
Different operating systems use varying types for file size and I/O operations:
- Windows relies on
LONGLONG(a signed 64-bit integer) for large file support. - Unix-like systems often use
off_t, which can be signed or unsigned depending on the platform and compilation flags.
By standardizing on qint64, Qt ensures consistent behavior across all platforms, avoiding pitfalls like unexpected overflow or comparison bugs that come with mixing signed and unsigned types.
4. Backward Compatibility
Qt’s I/O API was designed early on with signed integers for these methods, and maintaining backward compatibility is a core priority. Changing size() to quint64 would break existing code that relies on the signed return type—especially code that checks for -1 as an error indicator.
In short, even though file sizes are non-negative, Qt’s choice of qint64 balances interface consistency, error handling, cross-platform support, and backward compatibility.
内容的提问来源于stack exchange,提问作者CybeX

