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. 符合预期。