Nayana Adassuriya
Nayana Adassuriya

Reputation: 24766

Using static vector as a storage

My program has a enum to store colors and user response like this. Now I need to keep RGB and CYMK values along with the color. So this cannot do using enum,

enum COLOR
{
    RED = 'R',
    GREEN = 'G',
    BLUE = 'B',
    YELLOW = 'Y',
    MAGENTA = 'M'
};

So I' planing to use static array of struct for this purpose. I use static because

  1. These values are never change in the program
  2. To avoid multiple creation of the vector when other classes creating and destroying this classes object.

    struct Color
    {
     char user_responce;
     std::string rgb_code;
     std::string cymk_code;
    };
    
    static std::vector<Color> colors;
    colors.push_back('R', "FF0000", "30 - 96 - 76 - 26");
    

    But after reading this post Is using a lot of static methods a bad thing? I feel bad about the way I'm doing. Is this a "unsafe" statics? any other suggestion?

Upvotes: 1

Views: 368

Answers (1)

M.M
M.M

Reputation: 141554

If the values never change then you can do this:

static const std::vector<Colour> colors = 
{   { 'R', "FFFF00", "blabla" }
,   { 'S', "00FF00", "foo" }
,   { 'T', "0f3033", "burnt sienna" }
};

Personally I would use a C-style array and pointers to char here; in general those are bad idea but for static variables it removes the risk of undefined behaviour due to accessing an object that has not had its constructor called yet.

Upvotes: 2

Related Questions