当前位置:网站首页>QStringLiteral(str)
QStringLiteral(str)
2022-06-28 21:08:00 【Licht小粉】
在看项目代码的时候,总会看到下面这种情况
QString str = QStringLiteral("123rt");QString用QStringLiteral(str)来初始化,有点好奇,就查了下,记录一下。
这是用QStringLiteral初始化QString的原因:
使用 QStringLiteral 宏可以在编译期把代码里的常量字符串 str 直接构造为 QString 对象,于是运行时就不再需要额外的构造开销了。
这里补充一个知识隐含共享:
隐含共享在后台自动运行,所以我们不用再编写任何代码来促使这个优化过程发生。
举例说明:
QString srr1 = "happy";
QString str2 = str1;
此时QString的两个对象str1和str2都指向内存中相同的内部数据结构。与字符数据一起,数据结构保存一个引用计数,以指出有多少QString指向相同的数据结构。因为str1和str2都指向相同的数据,所以引用计数的值为2
str2[0] = 'D';
当修改str2时,它首先对数据进行深层复制,以确保str1和str2指向不同的数据结构,然后才将新数值应用于他复制的数据。此时str1和str2的引用计数都变成1了,引用计数变成1表示数据并未被共享。
str.truncate(4);
如果再次修改str2,由于str2的数据引用计数为1,将不会发生数据复制,truncate()函数直接对str2的数据进行操作,字符串变成Dappy,引用计数保持为1。
str1 = str2;
当将str2赋给str1时,str1的数据引用计数降为0,这意味着没有一个QString仍在使用“happy”数据。这样数据就从内存中释放了。两个QString都指向“Dappy”,现在它的引用计数就是2了。
由于引用计数中的竞争情况,数据共享在多线程程序中通常只是作为一个选项而没有给与关注。
边栏推荐
猜你喜欢
随机推荐
嵌入式中 动态阿拉伯语字符串 转换 LCD显示字符串【感谢建国雄心】
LeetCode226. 翻转二叉树
LeetCode117. 填充每个节点的下一个右侧节点指针_II
题解 The Blocks Problem(UVa101)紫书P110vector的应用
The principle and source code analysis of Lucene index construction
Bitbucket 使用 SSH 拉取仓库失败的问题
Résumé de la stabilité
Bitbucket 使用 SSH 拉取仓库失败的问题
ThreadLocal principle
LeetCode:合并K个升序链表_23
LeetCode123. The best time to buy and sell stocks III
ID access card copied to mobile phone_ How to turn a mobile phone into an access card mobile NFC copy access card graphic tutorial
[learning notes] cluster analysis
2. integrate filter
MongoDB——副本集与分片
How to analyze the relationship between enterprise digital transformation and data asset management?
LeetCode121. The best time to buy and sell stocks
APISIX 助力中东社交软件,实现本地化部署
Web自动化工具选择
Stability summary









