C++ Qt未记录的方法setharable
我偶然发现了一种方法,它似乎出现在所有数据对象中,如C++ Qt未记录的方法setharable,c++,qt,qlist,copy-on-write,C++,Qt,Qlist,Copy On Write,我偶然发现了一种方法,它似乎出现在所有数据对象中,如QList,QQueue,QHash 我甚至调查到目前为止,我可以看到它的源代码,这是 inline void setSharable(bool sharable) { if (!sharable) detach(); d->sharable = sharable; } 在(第117行) 但是它对QList,QQueue,QHash有什么影响呢?它是否与线程相关(听起来合理) 谢谢你的回答,请在你有实际知识的情况下回答。没有人能
QList
,QQueue
,QHash
我甚至调查到目前为止,我可以看到它的源代码,这是
inline void setSharable(bool sharable) {
if (!sharable) detach(); d->sharable = sharable;
}
在(第117行)
但是它对QList
,QQueue
,QHash
有什么影响呢?它是否与线程相关(听起来合理)
谢谢你的回答,请在你有实际知识的情况下回答。没有人能说得更清楚了: 以这种方式实现容器是常见的做法。您所询问的可共享状态与多线程无关。相反,它是将引用传递给内部状态的写时复制数据类(甚至是单线程数据类)的实现细节 考虑使用CoW实现的类
String
(为了便于说明,此类在线程上下文中不可用,因为对d->refcount
的访问不同步,它也不能确保内部char
数组以'\0'
结尾,还不如吃掉你的祖母;已经警告过你):
String s1("Hello World!");
char & W = s1[7]; // hold reference to the W
assert( W == 'W' );
const String s1(s2); // Shallow copy, but s1, s2 should now
// act independently
W = 'w'; // modify s1 _only_ (or so we think)
assert( W == 'w' ); // ok
assert( s1[7] == 'w' ); // ok
assert( s2[7] == 'W' ); // boom! s2[7] == 'w' instead!
为了防止出现这种情况,String
在发出对内部数据的引用时必须将其自身标记为不可共享,以便从中获取的任何副本都是深的。因此,我们需要像这样调整detach()
和char&operator[]
:
void detach() {
if (d->refcount == 1 && /*new*/ d->sharable)
return;
// rest as above
}
char & operator[](size_t idx) {
detach();
d->shareable = false; // new
return d->data[idx];
}
何时再次将可共享
状态重置为真
?一种常见的技术是,调用非常量方法时,对内部状态的引用无效,因此可共享
将重置为真
。因为每个非常量函数都调用分离()
,我们可以在那里重置可共享的,以便分离()
最终成为:
void detach() {
if (d->refcount == 1 && d->sharable) {
d->sharable = true; // new
return;
}
d->sharable = true; // new
StringRep * newRep = new StringRep(*d);
++newRep->refcount;
newRep->data = new char[d->size+1];
memcpy(newRep->data, d->data, d->size+1);
--d->refcount;
d = newRep;
}
虽然我搜索了qt文档,但我没有发现这一点。非常感谢
String s1("Hello World!");
char & W = s1[7]; // hold reference to the W
assert( W == 'W' );
const String s1(s2); // Shallow copy, but s1, s2 should now
// act independently
W = 'w'; // modify s1 _only_ (or so we think)
assert( W == 'w' ); // ok
assert( s1[7] == 'w' ); // ok
assert( s2[7] == 'W' ); // boom! s2[7] == 'w' instead!
void detach() {
if (d->refcount == 1 && /*new*/ d->sharable)
return;
// rest as above
}
char & operator[](size_t idx) {
detach();
d->shareable = false; // new
return d->data[idx];
}
void detach() {
if (d->refcount == 1 && d->sharable) {
d->sharable = true; // new
return;
}
d->sharable = true; // new
StringRep * newRep = new StringRep(*d);
++newRep->refcount;
newRep->data = new char[d->size+1];
memcpy(newRep->data, d->data, d->size+1);
--d->refcount;
d = newRep;
}