Qt 共享指针QSharedPointer与std::shared_ptr
- 引言
- 一、QSharedPointer简述及例程
- 二、std::shared_ptr简述及例程
引言
QSharedPointer
是 Qt 框架提供的智能指针,而 std::shared_ptr
是 C++ 标准库中的智能指针。两者均用于管理动态分配对象的生命周期。均支持自定义删除器,采用引用计数机制,线程安全,但指向的对象不是线程安全。引用计数:每创建一个指向同一对象的共享指针,引用计数加 1;每销毁一个共享指针,引用计数减 1。计数归零时自动释放内存。
一、QSharedPointer简述及例程
QSharedPointer
是 Qt 框架提供的共享指针类,用于自动管理动态分配的对象生命周期。其核心机制是通过引用计数实现共享所有权,当最后一个 QSharedPointer 释放对象时,自动删除托管对象。多个 QSharedPointer 实例可以共享同一对象的所有权,内部计数器记录引用数。当引用计数归零时,对象被自动销毁。支持通过 QSharedPointer<T, Deleter> 指定自定义删除逻辑。
- QSharedPointer的使用:https://zhuanlan.zhihu.com/p/718066552 - 使用Qt5没
useCount()
返回引用计数的函数. 不确定哪个版本引入. - qt中的共享指针,QSharedPointer类:https://blog.csdn.net/qq_42815643/article/details/129601509
- QSharedPointer的陷阱:https://blog.csdn.net/llq108/article/details/113461992
-
- 效果:创建后引用计数加1(函数值传递也算),离开作用域引用计数减1,引用计数为0时对象被销毁。

-
- 源码
#include <QCoreApplication>
#include <QSharedPointer>
#include <QDebug>
#include <iostream>struct test_struct{int64_t a;QString text;
};void doDeleteLater(test_struct *obj)
{qDebug() << "detele";
}void foo(QSharedPointer<test_struct> ptr){qDebug() << "foo: " << ptr->text;
}void fo(test_struct *test){QSharedPointer<test_struct> ptr(test);qDebug() << "before foo: " <<ptr->text;foo(ptr);qDebug() << "after foo: " <<ptr->text;
}int main(int argc, char *argv[])
{QCoreApplication a(argc, argv);test_struct *test = new test_struct;test->text = "123";qDebug() << "init text = " << test->text;fo(test);qDebug() << "auto delete: " << test->text;return a.exec();
}
二、std::shared_ptr简述及例程
std::shared_ptr
是 C++11 引入的智能指针,用于管理动态分配对象的生命周期。其核心特性是通过引用计数机制实现资源的自动释放,允许多个指针共享同一对象的所有权。当最后一个 shared_ptr 离开作用域时,对象会被自动销毁。
- C++11新特性 13.共享智能指针shared_ptr:https://blog.csdn.net/weixin_59409001/article/details/146164257
- C++智能指针之共享指针(std::shared_ptr):https://blog.csdn.net/flysnow010/article/details/138969826
-
- 效果:创建后引用计数加1(函数值传递也算),离开作用域引用计数减1,引用计数为0时对象被销毁。

-
- 源码
#include <iostream>
#include <memory>using namespace std;struct test_struct{int64_t a;std::string text;
};void foo(std::shared_ptr<test_struct> ptr){cout << "foo: " << ptr.use_count()<<endl;
}void fo(test_struct *test){std::shared_ptr<test_struct> ptr(test);cout << "before foo: " <<ptr.use_count() <<endl;foo(ptr);cout << "after foo: " <<ptr.use_count()<<endl;
}int main()
{test_struct *test = new test_struct;test->text = "123";cout<< "init text = " << test->text <<endl;fo(test);cout << "auto delete: " <<test->text<<endl;return 0;
}