How to initialize private static members in C++?

后端 未结 17 2287
忘掉有多难
忘掉有多难 2020-11-21 07:04

What is the best way to initialize a private, static data member in C++? I tried this in my header file, but it gives me weird linker errors:

class foo
{
           


        
17条回答
  •  不思量自难忘°
    2020-11-21 07:24

    If you want to initialize some compound type (f.e. string) you can do something like that:

    class SomeClass {
      static std::list _list;
    
      public:
        static const std::list& getList() {
          struct Initializer {
             Initializer() {
               // Here you may want to put mutex
               _list.push_back("FIRST");
               _list.push_back("SECOND");
               ....
             }
          }
          static Initializer ListInitializationGuard;
          return _list;
        }
    };
    

    As the ListInitializationGuard is a static variable inside SomeClass::getList() method it will be constructed only once, which means that constructor is called once. This will initialize _list variable to value you need. Any subsequent call to getList will simply return already initialized _list object.

    Of course you have to access _list object always by calling getList() method.

提交回复
热议问题