QT中的单例智能指针
1、首先创建一个客户类使用单例类。
头文件:
//--------------------------------------------------------------------------------------
#include
#include
#include
#include
class SingleSharePoint;
namespace Ui {
class Test;
}
class Test : public QMainWindow
{
Q_OBJECT
public:
explicit Test(QWidget *parent = 0);
~Test();
private slots:
void on_pushButton_clicked();
void on_pushButton_2_clicked();
private:
Ui::Test *ui;
};
//--------------------------------------------------------------------------------------
cpp文件:
#include “test.h”
#include “ui_test.h”
Test::Test(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::Test)
{
ui->setupUi(this);
}
Test::~Test()
{
delete ui;
}
void Test::on_pushButton_clicked()
{
SingleSharePoint::GetInstance(); //实例化
}
void Test::on_pushButton_2_clicked()
{
SingleSharePoint::destroy();//手动释放智能指针
}
//--------------------------------------------------------------------------------------
第二步创建单例智能指针。
头文件:
//--------------------------------------------------------------------------------------
class SingleSharePoint : public QObject
{
Q_OBJECT
private:
SingleSharePoint();
// ~SingleSharePoint();
static QSharedPointer p_Instance; // 定义为智能指针
static QMutex m_mutex;
static void deletepointr(SingleSharePoint *obj);
public:
static SingleSharePoint *GetInstance();
static void destroy();
};
//--------------------------------------------------------------------------------------
cpp文件:
//初始化
QMutex SingleSharePoint::m_mutex;
QSharedPointer SingleSharePoint::p_Instance;
SingleSharePoint::SingleSharePoint()
{
}
//私有化智能指针无法使用
//SingleSharePoint::~SingleSharePoint()
//{
// qDebug()<<“delete”;
//}
SingleSharePoint* SingleSharePoint::GetInstance()
{
//自动锁
QMutexLocker locker(&m_mutex);
if (p_Instance.isNull())
{
p_Instance = QSharedPointer(new SingleSharePoint,deletepointr); // 指定析构函数deletepointr
qDebug()<<“create”;
}
qDebug()<<“go”<<p_Instance;
}
//手动释放智能指针
void SingleSharePoint::destroy()
{
p_Instance.clear();
qDebug()<<“destroy”<<p_Instance;
}
// 智能指针指定的析构函数
void SingleSharePoint::deletepointr(SingleSharePoint* obj)
{
obj->deleteLater();
qDebug()<<“delete”;
}
//--------------------------------------------------------------------------------------
第三步 运行看结果,点击创建单例后,实例化一次。
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210316173751852.png
第四步删除,点击释放后,删除一次。
不对的请各位指出