栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

singleton模式 C++

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

singleton模式 C++

singleton 模式 C++ 基本形态
#include 
#include 

class TestSingleton
{

public:
     static TestSingleton *create_instance(void)
     {
         if (instance_ == nullptr) {
             instance_ = new TestSingleton();
             if (instance_ && instance_->init() < 0) {
                 std::cerr << "fail to create TestSingleton instance" 
                           << std::endl;
             }
         }
         return instance_;
     }
     void destroy(void) {
         delete instance_;
     }
     int print_name(void) {
         std::cout << name_ << std::endl;
     };
private:
    TestSingleton() {
        name_ = "TestSpace";
    }
    ~ TestSingleton() { };
    int init(void) {
        return 1;
    }
    static TestSingleton *instance_;
    std::string name_;
};

TestSingleton *TestSingleton::instance_ = nullptr;
  • 私有的静态指针变量,以及public的create_instance()函数
  • 私有的构造函数和析构函数(防止唯一实例在其他地方被创建)

(静态成员函数可以访问私有成员,唯一的区别是,静态成员函数没有this指针,只能用对象实例指针来访问私有成员)

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/849542.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号