C++使用shared_ptr和可变参数实现无内存泄漏的单例

技术原理:

  1. 私有化构造函数,析构函数,拷贝构造函数和赋值操作符,不让外部构造,并将默认函数实现设置为delete
  2. 使用std::shared_ptr管理单例内存,避免内存泄漏
  3. 使用可变参数模板构造任意对象

代码如下
singleton.hpp

#ifndef _SINGLETON_HPP_
#define _SINGLETON_HPP_
#include 

template 
using shared_ptr = typename std::shared_ptr;

template  
class Singleton {
    public:
        template  
        static shared_ptr&  Instance(Args&& ... args) {
            if(!m_pInstance) {
                m_pInstance = shared_ptr(new T(std::forward(args)...));
            }
            return m_pInstance;
        }

    private:
        static shared_ptr m_pInstance;
        Singleton() = delete;
        virtual ~Singleton() = delete;
        Singleton(const Singleton&) = delete;
        Singleton& operator=(const Singleton&) = delete;
};

template 
shared_ptr Singleton::m_pInstance = nullptr;

#endif

main.cpp

#include "singleton.hpp"
#include 
using std::cout;
using std::endl;

struct Person
{
    Person(): m_Name("呵呵"), m_Age(20) {

    }

    Person(std::string name, int age): m_Name(name), m_Age(age) {}

    std::string m_Name;
    int m_Age;
};

struct Visitor {
    Visitor(): m_Name("呵呵"), m_Age(20) {

    }
    std::string m_Name;
    int m_Age;
};

int main(void) {
    shared_ptr sInt = Singleton::Instance(100);
    cout << *sInt << endl;

    // 两次调用都获得 张三
    cout << "Person类相关信息输出: " << endl;
    shared_ptr p = Singleton::Instance("张三", 30);
    cout << "姓名: " << p->m_Name << " 年龄: " << p->m_Age << endl;
    shared_ptr p2 = Singleton::Instance();
    cout << "姓名: " << p2->m_Name << " 年龄: " << p2->m_Age << endl;

    // 调用无参构造函数
    cout << "Visitor类相关信息输出: " << endl;
    shared_ptr v = Singleton::Instance();
    cout << "姓名: " << v->m_Name << " 年龄: " << v->m_Age << endl;
}

Makefile

TAR=main
WORKSPACE_DIR=.
CC:=g++

.PHONY: build clear all

build:
    $(CC) -std=c++11 $(WORKSPACE_DIR)/*.*pp -g -o $(TAR)

all: clear build

clear:
    rm -rf $(TAR)

程序输出如下


图片.png

你可能感兴趣的:(C++使用shared_ptr和可变参数实现无内存泄漏的单例)