C ++: static initialize array member, member at a time

Now I can do it globally and everything works fine:

const char* Foo::bars[3] = {"a", "b", "c"}; 

But I want to do this because it is much more clear and self-complementary (especially if you use Enums as an index):

 const char* Foo::bars[3]; bars[0] = "a"; bars[1] = "b"; bars[2] = "c"; 

Is it possible?

I know that I can do this inside a function (for example, a class constructor), but what if the constructor is not called at the beginning of the program, and I want to use a static array? This leads to problems.

+4
source share
5 answers

In C ++, there is no equivalent to a static Java block.

If you really want to initialize the array automatically, you can create a simple class to do the job:

 // in .cpp class FooInitializer { public: FooInitializer() { Foo:bars[0] = "a"; Foo:bars[1] = "b"; Foo:bars[2] = "c"; } }; static FooInitializer fooInitializer; 
+1
source

How about this?

 const char* Foo::bars[3] = { /* Index Value */ /* 0 */ "a", /* 1 */ "b", /* 2 */ "c" }; 

I often use this โ€œtechniqueโ€ to initialize arrays of structures to look like a self-documenting table.

+7
source

You can use the accessor function:

 const char* GetArray() { static char* result[3]; static isInitialized = false; if (!isInitialized) { result[0] = "a"; result[1] = "b"; result[3] = "c"; initialized=true; } return result; } 
0
source

Here's another solution that uses the Singleton pattern. Note that the array is initialized once in a single constructor. Also note that this is not thread safe. Also beware of the evil of loners (find this site for "singleton" to find interesting discussions on this subject).

 #include <iostream> class StringTable { public: enum StringId { hello, bye, goodDay, stringCount }; static const char* lookup(StringId id) {return instance().table_[id];} private: StringTable() { table_[hello] = "Hello World!\n"; table_[bye] = "Goobye, cruel world!\n"; table_[goodDay] = "I said good day!\n"; } static StringTable& instance() { static StringTable theInstance; return theInstance; } const char* table_[stringCount]; }; int main() { std::cout << StringTable::lookup(StringTable::hello) << StringTable::lookup(StringTable::bye) << StringTable::lookup(StringTable::goodDay); } 
0
source

You probably need an extra constant in bars

 const char* const Foo::bars[3] = { "a", "b", "c" }; 

As you declared it, you can do what you need when setting up the members one at a time, although you must use the init function to do this.

If you want it to be const, which is probably preferable, it will subsequently become illegal to assign them a string at a time, even in some kind of โ€œinitโ€ method, and you should just use the code layout to make it clearer what you are doing .

0
source

Source: https://habr.com/ru/post/1337324/


All Articles