lundi 1 février 2021

Is it valid to set a member variable of Singleton Class directly?

I wonder the following code is valid, or not.

In main function, the 'testValue' of the member on 'testClass' will be set. If printed by calling 'showTestValue()' method, the variable must be updated? Or the variable may be not updated in some cases ?

#include <stdio.h>
#include <stdlib.h>

class testClass {
public:
    int testValue;
    static testClass* getInstance();

    void showTestValue();

private:
    testClass();
};

testClass*
testClass::getInstance()
{
    static testClass ins;
    return &ins;
}

testClass::testClass()
{
    testValue = 55;
}

void
testClass::showTestValue()
{
    printf("testVal is :%d\n", this->testValue);
}

int main(void)
{
    for(int i = 0; i < 100; ++i)
    {
        testClass::getInstance()->testValue = i;
        testClass::getInstance()->showTestValue();
    }
    exit(13);
}

Aucun commentaire:

Enregistrer un commentaire