(5)
/*
The QByteArray class provides an array of bytes.
QByteArray can be used to store both raw bytes (including '\0's) and
traditional 8-bit '\0'-terminated strings.
Using QByteArray is much more convenient than using const char *.
Behind the scenes, it always ensures that the data is followed by a '\0' terminator,
and uses implicit sharing (copy-on-write) to reduce memory usage and
avoid needless copying of data.
QByteArray 可以用于存储原始字节(包括"0')和传统8位"0'结尾的字符串。
使用-个"0'终OByteArray 比使用 const char*方便得多。
在后台,它始终确保数据后面跟着止符,并使用隐式共享(写时复制)来减少内存使用并避免不必要的复制数据。
除了QByteArray,Qt还提供了QString类来存储字符串数据。
对于大多数用途,QString是您想要使用的类。它将其内容理解为Unicode文本(使用UTF-16编码),
而QByteArray旨在避免对其存储的字节的编码或语义进行假设(除了少数使用ASCII的遗留情况)。
此外,QString在整个Qt API中都有使用。
QBvteArrav的两个主要适用情况是当您需要存储原始二进制数据时,
以及当内存保护至关重要时(例如,使用QtforEmbedded Linux)C
In addition to QByteArray, Qt also provides the QString class to store string data.
For most purposes, QString is the class you want to use.
It understands its content as Unicode text (encoded using UTF-16) where
QByteArray aims to avoid assumptions about the encoding or semantics of the bytes
it stores (aside from a few legacy cases where it uses ASCII).
Furthermore, QString is used throughout in the Qt API.
The two main cases where QByteArray is appropriate are when you need to store
raw binary data, and when memory conservation is critical
(e.g., with Qt for Embedded Linux).
One way to initialize a QByteArray is simply to pass a const char * to
its constructor. For example, the following code creates a byte array of
size 5 containing the data "Hello": QByteArray ba("Hello");
虽然size()是5,但字节数组在未尾还保留了的数据肯定以'0'结尾。个额外的'10'字节,
这样如果使用一个要求底层数据指针的函数(例如,调用 data 则指向.
QByteArray makes a deep copy of the const char * data,
so you can modify it later without experiencing side effects.
(If, for example for performance reasons, you don't want to take a deep copy of
the data, use QByteArray::fromRawData() instead.)
(例QByteArray对const char *data进行了深度复制,因此您可以在以后修改它而不会产生副作用。
如,出于性能原因,如果您不想对数据进行深度复制,请使用QByteArray::fromRawData()。)
Another approach is to set the size of the array using resize() and to
initialize the data byte by byte.
QByteArray uses 0-based indexes, just like C++ arrays.
To access the byte at a particular index position, you can use operator[]().
On non-const byte arrays, operator[]() returns a reference to a byte that
can be used on the left side of an assignment.
QByteArray ba; ba.resize(5); ba[0] = 0x3c;
For read-only access, an alternative syntax is to use at().
at() can be faster than operator[](), because it never causes a deep copy to occur.
To extract many bytes at a time, use first(), last(), or sliced().
A QByteArray can embed '\0' bytes.
The size() function always returns the size of the whole array, 整个数组
including embedded '\0' bytes, but excluding the terminating '\0' added by
QByteArray. For example:
QByteArray ba1("ca\0r\0t");
ba1.size(); // Returns 2.
ba1.constData(); // Returns "ca" with terminating \0.
QByteArray ba2("ca\0r\0t", 3);
ba2.size(); // Returns 3.
ba2.constData(); // Returns "ca\0" with terminating \0.
QByteArray ba3("ca\0r\0t", 4);
ba3.size(); // Returns 4.
ba3.constData(); // Returns "ca\0r" with terminating \0.
const char cart[] = {'c', 'a', '\0', 'r', '\0', 't'};
QByteArray ba4(QByteArray::fromRawData(cart, 6));
ba4.size(); // Returns 6.
ba4.constData(); // Returns "ca\0r\0t" without terminating \0.
If you want to obtain the length of the data up to and //等价于 strlen()的语义
excluding the first '\0' byte, call qstrlen() on the byte array.
After a call to resize(), newly allocated bytes have undefined values. 未定义的字节
To set all the bytes to a particular value, call fill().
To obtain a pointer to the actual bytes, call data() or constData().
These functions return a pointer to the beginning of the data.
The pointer is guaranteed to remain valid until a non-const function is called
on the QByteArray.
It is also guaranteed that the data ends with a '\0' byte unless the
QByteArray was created from raw data.
This '\0' byte is automatically provided by QByteArray and is not counted in size().
QByteArray provides the following basic functions for modifying the byte data:
append(), prepend(), insert(), replace(), and remove(). For example:
QByteArray x("and");
x.prepend("rock "); // x == "rock and"
x.append (" roll"); // x == "rock and roll"
x.replace(5, 3, "&"); // x == "rock & roll"
In the above example the replace() function's first two arguments are
the position from which to start replacing and the number of bytes that should
be replaced.
When data-modifying functions increase the size of the array,
they may lead to reallocation of memory for the QByteArray object.
When this happens, QByteArray expands by more than it immediately needs so as to
have space for further expansion without reallocation until the size of the
array has greatly increased.
The insert(), remove() and, when replacing a sub-array with one of different size,
replace() functions can be slow (linear time) for large arrays,
because they require moving many bytes in the array by at least
one position in memory.
If you are building a QByteArray gradually and know in advance approximately how
many bytes the QByteArray will contain, you can call reserve(),
asking QByteArray to preallocate a certain amount of memory.
You can also call capacity() to find out how much memory the QByteArray actually
has allocated.
Note that using non-const operators and functions can cause QByteArray to do
a deep copy of the data, due to implicit sharing. 隐式共享,所以能用常量函数就用常量函数
QByteArray provides STL-style iterators
(QByteArray::const_iterator and QByteArray::iterator).
In practice, iterators are handy方便 when working with generic algorithms
provided by the C++ standard library.
在实践中,当使用C++标准库提供的泛型算法时,迭代器非常方便。
Note: Iterators and references to individual QByteArray elements are subject to
stability issues. They are often invalidated when a QByteArray-modifying operation
(e.g. insert() or remove()) is called.
When stability and iterator-like functionality is required,
you should use indexes下标 instead of iterators as they are not tied to QByteArray's
internal state and thus do not get invalidated.
注意:迭代器和对单个QByteArray元素的引用可能会遇到稳定性问题。
当调用修改 QByteArray的操作(例如insert()或remove())时,它们通常会被无效化。
当需要稳定性和迭代器功能时,应使用索引而不是迭代器,因为它们不与 QByteArray的内部状态相关联,
因此不会被无效化
Note: Iterators over a QByteArray, and references to individual bytes within one,
cannot be relied on to remain valid when any non-const method of
the QByteArray is called. Accessing such an iterator or reference
after the call to a non-const method leads to undefined behavior.
When stability for iterator-like functionality is required,
you should use indexes instead of iterators as they are not tied to
QByteArray's internal state and thus do not get invalidated.
If you want to find all occurrences of a particular byte or sequence of bytes
in a QByteArray, use indexOf() or lastIndexOf().
The former searches forward starting from a given index position,
the latter searches backward.
Both return the index position of the byte sequence if they find it;
otherwise, they return -1.
If you simply want to check whether
a QByteArray contains a particular byte sequence, use contains().
If you want to find out how many times a particular
byte sequence occurs in the byte array, use count().
If you want to replace all occurrences of a particular value with another,
use one of the two-parameter replace() overloads.
QByteArrays can be compared using overloaded operators such as operator<(),
operator<=(), operator==(), operator>=(), and so on.
The comparison is based exclusively on the numeric values of the bytes and is
very fast, but is not what a human would expect.
QString::localeAwareCompare() is a better choice for sorting user-interface strings.
可以使用重载的运算符(如运算符<(),运算符<=()运算符==(),运算符>()等)来比较QByteArrays。
比较完全基于字节的数值,速度非常快,但并不符合人类的预期。
QString::localeAwareCompare()是用于排序用户界面字符串的更好选择.
For historical reasons, QByteArray distinguishes between a null byte array and
an empty byte array. A null byte array is a byte array that is initialized using
QByteArray's default constructor or by passing (const char *)0 to the constructor.
An empty byte array is any byte array with size 0.
A null byte array is always empty, but an empty byte array isn't necessarily null:
QByteArray().isNull(); // returns true
QByteArray().isEmpty(); // returns true
QByteArray("").isNull(); // returns false
QByteArray("").isEmpty(); // returns true
QByteArray("abc").isNull(); // returns false
QByteArray("abc").isEmpty(); // returns false
All functions except isNull() treat null byte arrays the same as empty byte arrays.
For example, data() returns a valid pointer (not nullptr) to a '\0' byte for
a null byte array and QByteArray() compares equal to QByteArray("").
We recommend that you always use isEmpty() and avoid isNull(). 推荐用isEmpty()
Maximum size and out-of-memory conditions:
The maximum size of QByteArray depends on the architecture.
Most 64-bit systems can allocate more than 2 GB of memory,
with a typical limit of 2^63 bytes. 【 overhead包括一切开支的;(费用等)管理的;】
The actual value also depends on the overhead required for managing the data block.
As a result, you can expect the maximum size of 2 GB minus overhead on
32-bit platforms, and 2^63 bytes minus overhead on 64-bit platforms.
The number of elements that can be stored in a QByteArray is this maximum size.
QByteArray 的最大大小取决于体系结构。大多数 64 位系统可以分配超过2GB 的内存,
通常限制为 2^63 字节。实际值还取决于管理数据块所需的开销。
因此,在32 位平台上,最大大小为2 GB 减去开销,在 64 位平台上最大大小为 2^63 字节减去开销。
可以存储在 QByteArray 中的元素数是此最大大小。
When memory allocation fails, QByteArray throws a std::bad_alloc exception if
the application is being compiled with exception support.
Out of memory conditions in Qt containers are the only case where Qt
will throw exceptions.
If exceptions are disabled, then running out of memory is undefined behavior.
Note that the operating system may impose further limits on applications holding
a lot of allocated memory, especially large, contiguous blocks.
Such considerations, the configuration of such behavior or
any mitigation缓解;减轻; are outside the scope of the QByteArray API.
请注意,操作系统可能会对占用大量分配内存的应用程序施加进一步的限制,特别是大且连续的块。
此类考虑、此类行为的配置或任何缓解措施超出了QByteArray API的范围。
C locale and ASCII functions :
QByteArray generally handles data as bytes, without presuming any semantics;
where it does presume semantics, it uses the C locale and ASCII encoding.
Standard Unicode encodings are supported by QString,
other encodings may be supported using QStringEncoder and
QStringDecoder to convert to Unicode. For locale-specific interpretation of text,
use QLocale or QString.
C Strings
Traditional C strings, also known as '\0'-terminated strings,
are sequences of bytes,
specified by a start-point and implicitly including each byte up to,
but not including, the first '\0' byte thereafter.
Methods that accept such a pointer, without a length,
will interpret it as this sequence of bytes.
Such a sequence, by construction, cannot contain a '\0' byte.
Other overloads accept a start-pointer and a byte-count;
these use the given number of bytes, following the start address,
regardless of whether any of them happen to be '\0' bytes.
In some cases, where there is no overload taking only a pointer,
passing a length of -1 will cause the method to use the offset of the
first '\0' byte after the pointer as the length;
a length of -1 should only be passed if the method explicitly says it does this
(in which case it is typically a default argument).
其他重载函数接受一个起始指针和一个字节数;
这些函数使用给定的字节数,从起始地址开始,无论它们是否碰巧是"0'字节。
在某些情况下,如果没有仅接受指针的重载,
传递长度为 -1将导致方法使用指针后第一个"0'字节的偏移量作为长度;
只有方法明确说明这样做时(在这种情况下,通常是一个默认参数),才应该传递长度为 -1。
Spacing Characters
A frequent requirement is to remove spacing characters from a byte array
('\n', '\t', ' ', etc.).
If you want to remove spacing from both ends of a QByteArray, use trimmed().
If you want to also replace each run of spacing characters with a single space
character within the byte array, use simplified().
Only ASCII spacing characters are recognized for these purposes.
Number-String Conversions
Functions that perform conversions between numeric data types and string
representations are performed in the C locale,
regardless of the user's locale settings.
Use QLocale to perform locale-aware conversions between numbers and strings.
执行数字数据类型和字符串表示之间的转换的函数在C区域设置中执行,无论用户的区域设置如何。
使用QLocale执行数字和字符串之间的区域感知转换。
Character Case
In QByteArray, the notion of uppercase and lowercase and of case-independent
comparison is limited to ASCII.
Non-ASCII characters are treated as caseless, since their case depends on encoding.
This affects functions that support a case insensitive option or
that change the case of their arguments.
Functions that this affects include contains(), indexOf(), lastIndexOf(),
isLower(), isUpper(), toLower() and toUpper().
This issue does not apply to QStrings since they represent characters using Unicode.
在QByteArray中,大写字母和小写字母的概念以及不区分大小写的比较仅限于ASCII。
非ASCII字符被视为不区分大小写,因为它们的大小写取决于编码。
这会影响支持不区分大小写选项或更改其参数大小写的函数。
受此影响的函数包括contains()、indexOf()、lastIndexOf()、isLower()、
isUpper()、0toLower()和toUpper()。
这个问题不适用于QStrings,因为它们使用Unicode表示字符:
*/
(6)
谢谢
250

被折叠的 条评论
为什么被折叠?



