gpt4 book ai didi

c++ - QByteArray : Is it safe to read from the array ('[ ]' ) between writes on the DataStream ('<<' )? 上的 QDataStream

转载 作者:行者123 更新时间:2023-11-28 04:17:55 26 4
gpt4 key购买 nike

我正在使用 QDataStream将数据(使用流的 << 运算符)序列化为 QByteArray .但我一直在想:从底层读取是否安全 QByteArray<< 之间操作(或者我可能会遇到缓冲问题)?

quint8 sumBytes(const QByteArray& byteArray)
{
//This will overflow quickly...
quint8 result = 0;
for (int i = 0; i < byteArray.size(); i++)
result += static_cast<quint8>(byteArray[i]);
return result;
}

QByteArrary createByteArray(qint32 foo, qint32 bar)
{
QByteArray array;
QDataStream stream(&array, QIODevice::ReadWrite);
stream<< foo;
stream<< bar;
// Safe to access array below?
const quint8 byteSum = sumBytes(array);
stream<< byteSum;
return array;
}

我已经检查了 QDataStream 的文档和 QByteArray但没有看到任何相关内容,除了提到 QDataStream使用 QBuffer作为QByteArray不是 QIoDevice (这让我问了这个问题)。再一次,QDataStream不提供 flush() (或类似的方法),所以它可能是安全的......?

最佳答案

当然。请记住,您已将 QByteArrayconst 版本传递给 sumBytes,这保证了对象的内部状态不会被改变。

您也可以考虑使用 .at() :

at() can be faster than operator[](), because it never causes a deep copy to occur.

(source)

关于c++ - QByteArray : Is it safe to read from the array ('[ ]' ) between writes on the DataStream ('<<' )? 上的 QDataStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56165990/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com