Question

For a singleton class in my system i had a hard time getting the destructor to be reported as "covered" during my class test (code coverage analysis part). I figured it was because the test framework was destructed before my static singleton instance was, and therefore i tried to change the destruction sequence by creating the singleton instance later - not at program startup.

My public getInstance method now looks like this:

SingletonClass* SingletonClass::getInstance()
{
  static SingletonClass instance;
  return &instance;
}

The constructor is private as usual but i don't have the classic singleton static instance pointer as a class member. Instead i have the instance stored as static function internal data (as shown above) which is created when the getInstance method is called for the first time.

I think the C++ standard says that static function internal variables are destructed in reverse order of creation. With this solution for getInstance the destructor is reported to be "covered" during class test code coverage analysis so it seems my theory is not proven wrong there at least.

This leads me to three questions:

  1. Could i have the more classic singleton implementation with a static class member instead, and call the destructor explicitely during a class test? What happens to the static data in that case, will it actually be deallocated?

  2. Does my theory regarding the order of destruction and impact on code coverage analysis seem completely unbelievable?

  3. Are there any obvious problems with my current implementation of getInstance? My program is single threaded.

Thanks

Was it helpful?

Solution

In C++ using class level static instance for singletone can be problematic. Since the order of initialization of two static object in different translation unit is undefined. Hence it is recommended to use Method level static object, which you did. In this case it is guaranteed to be initialized first time the method is called, also has the advantage of not creating the object if not needed.

Edit

I guessed it summarizes the answers:

  1. For C++, using statics method level is more secured
  2. Not to me
  3. For single threaded app, this is ok.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top