Austin K
Austin K

Reputation: 549

C++ large string initialization and use

Hi I have an array of around 500 strings. Multiple functions in my class use this variable. I obviously do not want to initialize that array multiple times throughout my program. What would be the most efficient method to initialize it once and be able to use it throughout the class?

Here is an example of what I mean:

SomeClass.h:

class SomeClass {
   public:
        static const std::string large_list[];
   private:
        void someFunc();
        void someFunc2();
        void someFunc3();
}

SomeClass.cpp:

void SomeClass::someFunc1(){
        static std::string large_list[] = {"something", "somethingelse", "somethingelse1"...};
        //do something with the large_list
   }

    void SomeClass::someFunc2(){
        static std::string large_list[] = {"something", "somethingelse", "somethingelse1"...};
        //do something with the large_list
   }

    void SomeClass::someFunc3(){
        static std::string large_list[] = {"something", "somethingelse", "somethingelse1"...};
        //do something with the large_list
   }

Thanks.

Upvotes: 0

Views: 911

Answers (1)

Jesse Good
Jesse Good

Reputation: 52365

You can use the following in-class initialization (note I didn't use std::string since it's constructor is not constexpr):

class SomeClass {
   public:
        static constexpr const char* large_list[] = {"something", "somethingelse", "somethingelse1"};
};

Upvotes: 1

Related Questions