使用C++ 11实现单例模式

C++ 单例模式在各种应用上使用都是比较广泛,但是在写单例模式的时候也需要考虑一些问题................

哎!不知道要怎么说了。  也不知道该如何解释了。  算了,直接上代码吧。

Singleton.hpp

#ifndef _SINGLETON_H_
#define _SINGLETON_H_

#include <mutex>
#include <memory>

template<typename C>
class Singleton
{
public:
	Singleton(const Singleton &) = delete;
	Singleton(Singleton &&) = delete;
	Singleton &operator=(const Singleton &) = delete;
	Singleton &operator=(Singleton &&) = delete;

protected:
	Singleton()
	{
	}
	virtual ~Singleton()
	{
	}
public:
 
	template<class... Args>
	static std::shared_ptr<C> Instance(Args&&... args)
	{
		static std::once_flag oc;
		std::call_once(oc, [&]{
			instance = std::make_shared<C>(std::forward<Args>(args)...);
		});
		return instance;
	}
private:
	static std::shared_ptr<C> instance;
};

 
template<typename C> 
	std::shared_ptr<C> Singleton<C>::instance = nullptr;

#endif // !_SINGLETON_H_

旧的:

#ifndef _SINGLETON_H_
#define _SINGLETON_H_

#include <mutex>
#include <memory>

template <typename C>
class Singleton
{
public:
    static C *Instance()
    {
        if (!instance)
        {
            std::lock_guard<std::mutex> lck(mtx);
            if (!instance) {
                instance = new C();
                //Destroy();
            }
            return instance;
        }
        return instance;
    }

protected:
    Singleton(void) = default;
    virtual ~Singleton(void) = default;

private:
    Singleton(const Singleton &) = delete;
	Singleton(Singleton &&) = delete;
	Singleton &operator=(const Singleton &) = delete;
	Singleton &operator=(Singleton &&) = delete;

    static void Destroy()
    {
        if (instance)
		{
			delete instance;
	        instance = nullptr;
		}
    }

    static C *instance;
    static std::mutex mtx;
};

template <typename C>
C *Singleton<C>::instance = nullptr;

template <typename T>
std::mutex Singleton<T>::mtx;

#endif // !_SINGLETON_H_

看上去是不是非常简洁。这个是一个通用的单例模式模板。主要是使用了以下:

1. delete关键字,将构造系列函数变成私有,有人说把这些写进private,这样也是可以的,  但是我个人还是比较喜欢使用delete,而且也符合C++ 11以后的写法

2.使用shared_ptr智能指针,  这个好处就不用多少了,  可以自动管理内存

3.使用lambda表达式配合std::call_once 函数,实现线程安全,并且让代码开起来更加清晰

<std::call_once可以保证多个线程对该函数只调用一次。也可用在解决线程安全的单例模式>

以下是调用方法:

main.cpp

#include <iostream>
#include "design/Singleton.hpp"


class MyClass
{
public:
    MyClass()
        :m_value(10)
    {}

    MyClass(int value)
        :m_value(value)
    {}

    ~MyClass()
    {
        std::cout << "xigou" << std::endl;
    }
	
	void destory()
	{
		std::cout << "destory" << std::endl;
	}

    void print()
    {
        std::cout << m_value << std::endl;
    }
private:

    int m_value;
};



int main(int argc, char const *argv[])
{
    auto sg1 = Singleton<MyClass>::getInstance();
    sg1->print();


    auto sg2 = Singleton<MyClass>::getInstance();
    sg2->print();

    return 0;
}

例子非常简单,  就是写一个类,  之后调用。   大家可以调试下,看看调用流程,这个不做过多解释

 

以下是CMakelists.txt

cmake_minimum_required(VERSION 3.5 FATAL_ERROR)

project(desgin_test)

if (WIN32)
    message(STATUS "sys is windows")
elseif (APPLE)
    message(STATUS "sys is Apple systems.")
elseif (UNIX)
	message(STATUS "sys is UNIX-like OS's.")
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} --std=c++14")
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -O2 -g -Wall -pthread")
    set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -lthread")
endif()

aux_source_directory(. src_lists)


add_executable(${PROJECT_NAME} ${src_lists})

好吧,  到此结束。

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值