多个单例对象,析构顺序模拟

it2022-05-05  272

#include <iostream> #include <unistd.h> using namespace std; struct StaticMember { public: int age = 6; StaticMember() { std::cout << "StaticMember()" << std::endl; } ~StaticMember() { std::cout << "~StaticMember()" << std::endl; } }; struct StaticMember2 { StaticMember2() { std::cout << "StaticMember2()" << std::endl; } ~StaticMember2() { std::cout << "~StaticMember2()" << std::endl; } }; struct PlainMember { PlainMember() { std::cout << "PlainMember()" << std::endl; } ~PlainMember() { std::cout << "~PlainMember()" << std::endl; } }; struct PlainMember2 { PlainMember2() { std::cout << "PlainMember2()" << std::endl; } ~PlainMember2() { std::cout << "~PlainMember2()" << std::endl; } }; struct StaticMember3 { StaticMember3() { std::cout << "StaticMember3()" << std::endl; } ~StaticMember3() { std::cout << "~StaticMember3()" << std::endl; } }; class MyClass { public: static MyClass *GetInstance() { static MyClass a; return &a; } static StaticMember3*getStatic() { static StaticMember3 pl3; return &pl3; } static void print() { getStatic(); std::cout << "/* message */" << std::endl; } private: MyClass(); ~MyClass(); public: PlainMember2 plainMember2; PlainMember plainMember; static StaticMember2 staticMember2; static StaticMember staticMember; }; MyClass::MyClass() { std::cout << "MyClass()" << std::endl; } MyClass::~MyClass() { print(); std::cout << "~MyClass()" << std::endl; std::cout << "~MyClass():~StaticMember(),age:" << staticMember.age << std::endl; } StaticMember MyClass::staticMember; StaticMember2 MyClass::staticMember2; int main(int argc, const char **argv) { // std::cout << MyClass::GetInstance()->staticMember.age ; //<< std::endl; //std::cout << MyClass::getStatic() << std::endl; return 0; }

最新回复(0)