1

I have some code like this:

Class: CreateList.h

class CreateList {
public:

    static CreateList* GetInstance( VOID )
    {
        static CreateList Instance;
        return &Instance;
    }
}

When i built, i get warning in static CreateList Instance;

Declaring modifiable local static variable Instance in an external inline function.

So i try remove static in static CreateList Instance and then get warning:

Returning the address of a stack variable "Instance".

How to fix this warning?

Nimantha
  • 6,405
  • 6
  • 28
  • 69
Huy Nguyen
  • 63
  • 9

1 Answers1

2

The warning doesn't apply to standard C++, so if you don't rely on language extensions, then the warning can be safely ignored and disabled.

Some dynamic loading extensions do apparently have conformance problems, so if the function may be included into a shared library, then the warning should be fixed.


How to fix this warning?

By analysing the wording of the warning message, we can deduce modifications that would make it not match the function anymore:

  • Make the function non-inline. This can be achieved by defining the function outside of the class definition in a separate translation unit. This change wouldn't change the semantics of the program, so it should be safe.
  • Use a namespace scope variable instead of a local static one. Be very careful to avoid Static Initialisation Order Fiasco. Also, the variable probably has to be non-inline.
  • Define the entire class in an unnamed namespace, thereby making the linkage internal. Take into consideration how this makes separate translation units have distinct static objects, and determine whether that conforms to the requirements of your program.

P.S. I recommend returning a reference instead of pointer. I see no drawbacks in doing so.

eerorika
  • 232,697
  • 12
  • 197
  • 326