//test.cpp
void fun1();
void fun2();
int main()
{
fun1();
fun2();
}
//single1.cpp
#include <iostream>
using namespace std;
class single
{
private:
string name;
~single()
{
cout << "single1 go" << endl;
}
single()
{
name = "single1";
}
friend ostream& operator<<(ostream& os, single& ptr)
{
return cout << ptr.name << endl;
}
public:
single(single const&) = delete;
void operator=(single const&) = delete;
static single& get_instance()
{
static single thissingle;
return thissingle;
}
};
void fun1()
{
cout << &single::get_instance() << endl;
}
//single.cpp
#include <iostream>
using namespace std;
class single
{
private:
string name;
~single()
{
cout << "single2 go" << endl;
}
single()
{
name = "single2";
}
friend ostream& operator<<(ostream& os, single& ptr)
{
return cout << ptr.name << endl;
}
public:
void funnnn()
{
cout << "add fun" << endl;
}
single(single const&) = delete;
void operator=(single const&) = delete;
static single& get_instance()
{
static single thissingle;
return thissingle;
}
};
void fun2()
{
cout << &single::get_instance() << endl;
single::get_instance().funnnn();
}
输出:
00007FF6B5F65640
00007FF6B5F65640
add fun
single1 go
结论:
- 是生成的同一个类,但是是根据single1.cpp中的定义来实现的。
- 无论我是先调用fun1()还是fun2(),生成的都是single1.cpp中定义的实例。
- 有趣的是,如果在single2中调用funnnn(),那么也能成功调用!所以这个实例到底是什么性质,依据什么来初始化?我的知识量还不能找到答案。