当前位置:网站首页>Qt 中的隐式共享
Qt 中的隐式共享
2022-08-11 01:18:00 【litanyuan】
背景
Qt 中的许多类都是使用隐式共享来最大化资源使用并最小化复制。其进行参数传递时采用浅拷贝方式,只传递指向数据的指针,并且只有在数据写入时才真的拷贝数据。
通过使用 Qt 提供的相关类,可以实现自定义的隐式共享类。
Qt 中的隐式共享
①.概述
Qt 中的 QString 是具有隐式共享特性的类。
②.代码示例
QString s1 = "hello world";
QString s2 = s1;
qDebug() << s1.constData();
qDebug() << s2.constData();
如上图所示,s1 和 s2 中包含的数据指向同一个地址,但如果一个字符串发生更改时,将会进行写时拷贝操作:
QString s1 = "hello world";
QString s2 = s1;
qDebug() << s1.constData();
qDebug() << s2.constData();
s2[0] = 'H';
qDebug() << "s2 更改后:";
qDebug() << s1.constData();
qDebug() << s2.constData();
隐式共享相关类
①.概述
Qt 提供了一套包含隐式共享机制的一些类。
②.QSharedData
QSharedData 是实现共享数据对象的基类。
③.QSharedDataPoint
QSharedDataPoint 是一个模板类,和 QSharedData 一起使用来实现隐式数据共享。
自定义隐式共享类
①.概述
使用 QSharedData 和 QSharedDataPoint 可以实现自定义的隐式共享类。
②.代码示例
struct demoClassData :public QSharedData
{
demoClassData(){
}
demoClassData(int m_id,const QString &m_name) :id(m_id), name(m_name){
}
int id{
-1};
QString name;
};
class demoClass
{
public:
demoClass():d(new demoClassData){
}
demoClass(int m_id, const QString &m_name):d(new demoClassData(m_id, m_name)) {
}
void setId(int m_id) {
d->id = m_id; }
void setName(const QString &m_name) {
d->name = m_name; }
void printData() {
qDebug() << d.constData(); }
private:
QSharedDataPointer<demoClassData> d;
};
demoClass d1(1, "aaaa");
demoClass d2 = d1;
d1.printData();
d2.printData();
d2.setName("bbbb");
qDebug() << "数据修改后";
d1.printData();
d2.printData();
边栏推荐
猜你喜欢
Pico 4更多参数曝光:Pancake+彩色透视,还有Pro版本
[21 Days Learning Challenge] Half Insertion Sort
什么是“门”电路(电子硬件)
Web APIs BOM - A Comprehensive Case of Operating Browsers
力扣------使用最小花费爬楼梯
异常和异常处理机制
【Video】Report Sharing | 2021 Insurance Industry Digital Insights
两日总结十
Shell编程三剑客之sed
#yyds干货盘点#【愚公系列】2022年08月 Go教学课程 008-数据类型之整型
随机推荐
C# using timer
SystemVerilog: 验证知识点点滴滴
url转成obj或者obj转成url的方法
力扣------值相等的最小索引
15 DOM 扩展
22. Inventory service
Shell 文本三剑客 Sed
【服务器数据恢复】raid5崩溃导致lvm信息和VXFS文件系统损坏的数据恢复案例
【Video】Report Sharing | 2021 Insurance Industry Digital Insights
简陋的nuxt3学习笔记
Linux install redis database
what is an array
微信小程序内部A页面向内嵌H5页面跳转,并且传参
Distributed. Performance optimization
The statistical data analysis, interview manual"
云原生-VMware虚拟机安装Kubesphere实战(一)
Update chromedriver driver programming skills │ selenium
BEVDepth: Acquisition of Reliable Depth for Multi-view 3D Object Detection Paper Notes
③ 关系数据库标准语言SQL 数据查询(SELECT)
apache+PHP+MySQL+word press,安装word press时页面报错?