单件模式与智能指针、友元类的结合
单件模式与智能指针结合
c++11 引入了智能指针std::unique_ptr、std::shared_ptr、std::weak_ptr,都2020年了,你还在用那些老掉牙的c++98遗留代码来实现吗?是时候体验一把Effective Modern C++的酸爽了。废话不说,直接上代码,码友可以多方体会。
/*
* Filename: singletons_smart_pointer.cpp
*
* Copyright (C) 2018-2023 eric <eric@company.com>. All Rights Reserved.
*
* History:
* 2020/08/01 - [eric] Created file
*
* Maintainer: eric <eric@email.com>
* Created: 2020-08-01
* LastChange: 2020-08-01
* Version: v0.0.01
*
*/
#include <iostream>
#include <memory>
class Singleton
{
public:
static std::shared_ptr<Singleton> Get();
~Singleton() {}
private:
Singleton() {};
static std::weak_ptr<Singleton> singleton_;
};
std::weak_ptr<Singleton> Singleton::singleton_;
std::shared_ptr<Singleton> Singleton::Get()
{
std::shared_ptr<Singleton> instance = singleton_.lock();
if (!instance) {
printf("%s: create an object\n", __func__);
instance.reset(new Singleton());
singleton_ = instance;
} else {
printf("%s: exist object\n", __func__);
}
return instance;
}
int main(int argc, char *argv[])
{
auto singleton = Singleton::Get();
auto singleton2 = Singleton::Get();
return 0;
}