1,智能指针,shared_ptr<>
放在.h中
std::shared_ptr<类别>nav(){ return nav_};
std::shared_ptr<类别>nav_ = nullptr;
放在.cpp中
if(!nav_) nav_ = std::make_shared<类别>();//初始化
2,单例模式,instance
放在global_def.h
#defline ROSCI Roscommunition::instance()
在roscommunication.h中
class Roscommunition{
public:
static Roscommunication* instance (std::string ns=" ");
}
调用:
ROSCI--->(class Roscommunition中的函数)
确保一个类只有一个实例被建立
提供了一个对象的全局访问指针
在不影响单例类的客户情况下将来可以有多个实例
class CSingleton
{
public:
static CSingleton* GetInstance()
{
if ( m_pInstance == NULL )
m_pInstance = new CSingleton();
return m_pInstance;
}
private:
CSingleton(){};
static CSingleton * m_pInstance;
};
初始化:
CSingleton* p1 = CSingleton :: GetInstance();
CSingleton* p2 = p1->GetInstance();
CSingleton & ref = * CSingleton :: GetInstance();
改进版本的懒汉式:
class CSingleton
{
private:
CSingleton()
{
}
static CSingleton *m_pInstance;
class CGarbo
{
public:
~CGarbo()
{
if(CSingleton::m_pInstance)
delete CSingleton::m_pInstance;
}
};
static CGarbo Garbo;
public:
static CSingleton * GetInstance()
{
if(m_pInstance == NULL)
m_pInstance = new CSingleton();
return m_pInstance;
}
};
特点:
当程序运行结束时,会自动的调用CSingleton的静态成员Garbo的析构函数,删除单例的唯一实例
在单例类内部定义专有的嵌套类
在单例类内定义私有的专门用于释放的静态成员
利用程序在结束时析构全局变量的特征,选择最终的释放时机
3,饿汉式
实现:
class CSingleton
{
private:
CSingleton()
{
}
public:
static CSingleton * GetInstance()
{
static CSingleton instance;
return &instance;
}
};
特点:
线程是安全的,在类的创建的同时就建好一个静态的对象提供给系统使用
C++11线程安全:
/// 内部静态变量的懒汉实现 //
class Single
{
public:
// 获取单实例对象
static Single &GetInstance();
// 打印实例地址
void Print();
private:
// 禁止外部构造
Single();
// 禁止外部析构
~Single();
// 禁止外部复制构造
Single(const Single &signal);
// 禁止外部赋值操作
const Single &operator=(const Single &signal);
};
Single &Single::GetInstance()
{
// 局部静态特性的方式实现单实例
static Single signal;
return signal;
}
void Single::Print()
{
std::cout << "我的实例内存地址是:" << this << std::endl;
}
Single::Single()
{
std::cout << "构造函数" << std::endl;
}
Single::~Single()
{
std::cout << "析构函数" << std::endl;
}
/// 内部静态变量的懒汉实现 //