gpt4 book ai didi

c++ - 在稍后调用删除的对象上工作是否安全

转载 作者:行者123 更新时间:2023-11-30 02:57:43 25 4
gpt4 key购买 nike

我在想这样的写法:

QString getData() {
QNetworkReply *reply = getReply();
reply->deleteLater();
return QString::fromUtf8(reply->readAll()).trimmed();
}

安全吗?如果我被迫这样写:

QString getData() {
QNetworkReply *reply = getReply();
QString result = QString::fromUtf8(reply->readAll()).trimmed();
reply->deleteLater();
return result;
}

我正在处理 QString 两次(是吗?一次是将其放入结果,第二次是按值返回),我想避免这种情况。

最佳答案

来自deleteLater文档:

Schedules this object for deletion.

The object will be deleted when control returns to the event loop. If the event loop is not running when this function is called (e.g. deleteLater() is called on an object before QCoreApplication::exec()), the object will be deleted once the event loop is started.

所以你在那里做的事情是安全的。显然,分发指向该对象(或其成员)的引用或指针可能会被持久化是错误的。但如果您要退回拷贝,则没有问题。

但是您正在做的事情可能会或可能不会做您想做的事情。 readAll 不会阻塞,它返回当前可用 的数据。这意味着对 readAll 的一次调用可能只会读取部分响应 - 除非您确保所有数据都已通过其他方式到达。

其他需要注意的事项,来自文档:

Note that entering and leaving a new event loop (e.g., by opening a modal dialog) will not perform the deferred deletion; for the object to be deleted, the control must return to the event loop from which deleteLater() was called.

所以在做这种事情时唯一要担心的是调用以某种方式重新进入“当前”事件循环的函数。但如果通过 QCoreApplication::processEvents 完成,那将不会发生。 :

In event you are running a local loop which calls this function continuously, without an event loop, the DeferredDelete events will not be processed.

所以这也包括在内。延迟删除逻辑相当复杂,但在正常情况下是安全的。如果您正在深入挖掘 Qt 内部结构(或调用可能在那里做一些可疑的代码),请采取防御措施。但是对于正常的代码流,只要您没有可能持续存在的悬挂引用(或指针),deleteLater 就是安全的。

关于c++ - 在稍后调用删除的对象上工作是否安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14294982/

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