Qt 未记录的方法 setSharable
我偶然发现了一种方法,它似乎存在于所有数据对象中,例如 QList、QQueue、QHash...
到目前为止我什至进行了调查可以看到它的源代码,位于
inline void setSharable(bool sharable) {
if (!sharable) detach(); d->sharable = sharable;
}
qlist 中。 h(第 117 行)。
但它对 QList、QQueue、QHash 等有什么影响呢?它与线程有什么关系吗(这听起来很合理)?
感谢您的任何回答,请仅在您有实际知识的情况下回答。
I stumbled about a method which seems to be present in all data objects like QList
, QQueue
, QHash
...
I even investigated so far I can see the source code of it, which is
inline void setSharable(bool sharable) {
if (!sharable) detach(); d->sharable = sharable;
}
in qlist.h (lines 117).
But what effect does it have on the QList
, QQueue
, QHash
... ? And is it in any way related to threading (which sounds reasonable)?
Thanks for any answer, and please only answer if you got actual knowledge.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
没有人能说得更清楚了:
http://qt.nokia.com/doc/ 4.6/implicit-sharing.html
以这种方式实现容器是常见的做法。
No one could say more clear:
http://qt.nokia.com/doc/4.6/implicit-sharing.html
It is common practice to realize containers this way.
您所询问的可共享状态与多线程无关。相反,它是写时复制数据类(甚至是单线程数据类)的实现细节,用于分发对内部状态的引用。
考虑使用 CoW 实现的类
String
(出于说明目的,此类在线程上下文中不可用,因为对d->refcount
的访问不同步,它也不能确保内部char
数组以'\0'
结尾,并且可能会吃掉你的祖母):还有一个示例 ; function each 用于 mutating 和 const 方法:
到目前为止一切顺利。但是如果我们想提供一个可变的
operator[]
怎么办?这种幼稚的实现有一个缺陷。考虑以下场景:
为了防止这种情况,
String
在发出对内部数据的引用时必须将自己标记为不可共享,以便从中获取的任何副本始终是深的。因此,我们需要调整detach()
和char &像这样的operator[]
:什么时候再次将
shareable
状态重置回true
?一种常见的技术是在调用非常量方法时对内部状态的引用无效,因此这就是将shareable
重置回true
的地方。由于每个非常量函数都会调用detach()
,我们可以在那里重置shareable
,这样detach()
最终会变成:The sharable state you're asking about has nothing to do with mutlithreading. It is instead an implementation detail of copy-on-write data classes (even single-threaded ones) that hand out references to internal state.
Consider a class
String
that is implemented using CoW (for illustration purposes, this class isn't usable in threaded contexts, because accesses tod->refcount
aren't synchronised, it also doesn't ensure that the internalchar
arrary ends in'\0'
, and might as well eat your grandmother; you have been warned):And a sample function each for mutating and const methods:
So far so good. But what if we want to provide a mutable
operator[]
?This naïve implementation has a flaw. Consider the following scenario:
To prevent this,
String
has to mark itself non-sharable when it hands out a reference to internal data, so that any copy that is taken from it is always deep. So, we need to adjustdetach()
andchar & operator[]
like this:When to reset the
shareable
state back totrue
again? A common technique is to say that references to internal state are invalidated when calling a non-const method, so that's whereshareable
is reset back totrue
. Since every non-const function callsdetach()
, we can resetshareable
there, so thatdetach()
finally becomes: