A better way to initialize a static array member of a class in C++ ( const would be preferred though )

点点圈 提交于 2019-12-12 01:59:06

问题


I have a static array of pointers to functions as a member of a class.

I need to initialize it, but it turns out this array is 64K items long, so it's impractical to initialize it with a static initializer like { x, y, z, ... } as it would clutter code.

I have instead to initialize it by code, with several loops.

The way I figured to do this is by initializing the static array in the constructor and setting a flag to it, so only the construction of the first instance of the class would fire this initialization.

Also accessing this static flag from within instances would not be thread safe, but that's another story.

Is there a cleaner or better way of doing this?

I also would like this array to be const, but I'm afraid the only way to do it is with the static {} initialization, right?


回答1:


Another option would be to use code generation: Write a separate program that generates the source code for the definition of the static array.




回答2:


Maybe not the cleaniest code, but how about making the member array a static reference;

header file:

class MyClass
{
    ...
    static const std::vector<pointer to member>& pointer_vector;
};

implementation file:

namespace
{
    typedef std::vector<pointer to member> t_pointer_vector;

    t_pointer_vector pointer_vector;

    const t_pointer_vector& initialize_pointer_vector(void)
    {
        //generate pointer_vector

        return pointer_vector;
    }
}

t_pointer_vecotor& MyClass::pointer_vector = initialize_pointer_vector();

If you don't want std::vector, you can take a look at std::tr1::array, a fixed size array that is safer than and no less efficient than a C style array (according to Boost doc). It is a part of TR1. Basic info about TR1 can be found on wikipedia, its documentation under Boost.



来源:https://stackoverflow.com/questions/8108321/a-better-way-to-initialize-a-static-array-member-of-a-class-in-c-const-would

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!