There is a singleton class for covering tests using the gmock framework . Some methods (such as method1 () in the example) change the class field values ​​during a call. Is there any way to set default values ​​to class fields without changing the class structure?

Example:

class TestingClass { private: TestingClass(): _field1(0) , _field2(0) { } TestingClass(const TestingClass&){} TestingClass & operator=(const TestingClass &){} public: static TestingClass Instance() { static TestingClass instance; return instance; } void method1() { _field1 = 777; } void method2() { _field1 = 888; } void Show() { std::cout << "\nField1 - " << _field1 << "\nField2 - " << _field2 << "\n"; } //other methods... private: int _field1; int _field2; }; 
  • one
    unless in the designer _field1 (0), you do not set default values? - Unick
  • maybe the problem is that in Instance () I need to return the link? static TestingClass& Instance() - goldstar_labs

1 answer 1

For guaranteed initialization, use Singlels Myers:

 Foo& fooInstance(){ static Foo value (init_value); return value; } 

Or so:

 Foo& fooInstance(){ static Foo value = []{ Foo initValue; initValue.setValue(42); return initValue; }(); return value; } 

Anywhere you call this function, the correct link will be returned. In the case of possible multi-threading, the class Foo itself must be thread-safe, then the singleton will be thread-safe (starting with C ++ 11).

PS In your code, it is enough to initialize the class fields in the constructor and return the link to the instаnce , and not copy the object.