欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Tars框架单例模式TC_Singleton的使用

程序员文章站 2022-07-14 09:16:29
...

TC_Singleton可以有选择在静态区域或堆上创建对象,下面用一个实例跑一下:
代码如下:

	// 静态区创建 static
    class TestCreateStaticObj : public TC_Singleton<TestCreateStaticObj, CreateStatic, PhoneixLifetime>
    {
    public:
        TestCreateStaticObj()
        {
            cout << "TestCreateStaticObj()" << endl;
        }

        ~TestCreateStaticObj()
        {
            cout << "~TestCreateStaticObj()" << endl;
        }

    public:
        void test()
        {
            cout << " test TestCreateStaticObj" << endl;
        }
    };

	// 堆上创建
    class TestUsingNewObj : public TC_Singleton<TestUsingNewObj, CreateUsingNew, PhoneixLifetime>
    {
    public:
        TestUsingNewObj()
        {
            cout << "TestUsingNewObj()" << endl;
        }

        ~TestUsingNewObj()
        {
            cout << "~TestUsingNewObj()" << endl;
        }
    public:
        void test()
        {
            cout << " test TestUsingNewObj" << endl;
        }
    };

主测试代码如下:

    class TestSinglton 
    {
    public:
        static void test()
        {
            try
            {
                auto obj1 = TestCreateStaticObj::getInstance();
                obj1->test();
                auto obj11 = TestCreateStaticObj::getInstance();
                obj11->test();

                // 看变量所在区 声明一个static int变量,将变量地址对比粗略确定对象所在区域
                static int staticValue = 0;
                cout << "staticValue address: \t\t" << &staticValue << endl;
                cout << "TestCreateStaticObj address: \t" << obj1 << endl;

                cout << endl;
                auto obj2 = TestUsingNewObj::getInstance();
                obj2->test();
                auto obj22 = TestUsingNewObj::getInstance();
                obj22->test();

                // 看变量所在区 声明一个堆上的变量,将变量地址对比粗略确定对象所在区域
                int* heapValue = new int[1];
                cout << "heapValue address: \t\t" << heapValue << endl;
                cout << "TestUsingNewObj address: \t" << obj2 << endl;
                delete[] heapValue; heapValue = nullptr;
            }
            catch (const std::exception& ex)
            {
                cout << ex.what() << endl;
            }
        }
    };

执行结果:

    [email protected]:~/projects/FishTars/bin/x64/Debug$ ./FishTars.out
    TestCreateStaticObj()
     test TestCreateStaticObj
     test TestCreateStaticObj
    staticValue address:            0x60a4dc
    TestCreateStaticObj address:    0x60a4e0

    TestUsingNewObj()
     test TestUsingNewObj
     test TestUsingNewObj
    heapValue address:              0x205d030
    TestUsingNewObj address:        0x205d010
    ~TestUsingNewObj()
    ~TestCreateStaticObj()

实践环境:vs2017+ubuntu14.04
代码路径:
https://github.com/lesliefish/FishTars/blob/master/code/FishTars/test/utiltest/test_singleton.h