c++ 单例模式

MySingleton.h头文件内容:

cpp 复制代码
#pragma once
#include <iostream>

class MySingleton
{
public:
	static MySingleton& getInstance() { // 单例,  搜了下静态成员函数中含有静态局部变量, 建议把函数实现放在头文件,成为隐式内联函数
		static MySingleton instance; // 局部静态变量,c++11保证其线程安全
		return instance;
	}

	// 禁止拷贝和赋值
	MySingleton(const MySingleton&) = delete;
	MySingleton& operator=(const MySingleton&) = delete;

	~MySingleton();

	void print() const;

	void setAge(int age);

private:
	MySingleton() = default; // = default表示显式要求编译器生成该构造函数的默认实现

	int age;
};

MySingleton.cpp源文件:

cpp 复制代码
#include "MySingleton.h"

MySingleton::~MySingleton() { std::cout << "析构MySingleton" << std::endl; }

void MySingleton::print() const {
	std::cout << "age: " << age << std::endl;
}

void MySingleton::setAge(int age) {
	this->age = age;
}

测试代码:

cpp 复制代码
#include "MySingleton.h"

void testSingleTon() {
	MySingleton& singleton = MySingleton::getInstance();
	singleton.setAge(9527);
	
	MySingleton* singleton2 = &MySingleton::getInstance();
	singleton2->print();
}

打印:

ok. 符合预期。

相关推荐
肆忆_13 小时前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星17 小时前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛2 天前
delete又未完全delete
c++
端平入洛3 天前
auto有时不auto
c++
郑州光合科技余经理4 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1234 天前
matlab画图工具
开发语言·matlab
dustcell.4 天前
haproxy七层代理
java·开发语言·前端
norlan_jame4 天前
C-PHY与D-PHY差异
c语言·开发语言
哇哈哈20214 天前
信号量和信号
linux·c++
多恩Stone4 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc