Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New Coder
    Join Date
    Jan 2005
    Posts
    74
    Thanks
    0
    Thanked 1 Time in 1 Post

    Question How to create a static map that is only loaded once? [C++]

    Not sure this is going to be easy to explain but ...
    I have a class (A) that needs to have access to a map (mapCodes), this map is the same for all instances of class(A), therefore I don't want to create an instance of the map for each instance of class A and populate it, etc ....

    This is my code right now:

    A.h (header file)
    Code:
    class A
    {
    private:
    	static map<int, string> mapCodes;
    
    public:
    	A();	// constructor
    };
    A.cpp (header file)
    Code:
    A::A
    {
    	mapCodes[1] = "AAA";
    	mapCodes[2] = "BBB";
    	mapCodes[3] = "CCC";
    
    }
    Now, for every object of class A I call the constructor which uses the same STATIC mapCodes (which is good) but the constructor also repopulates it each time ... what a waste ...
    Isn't there a way I can ... declare mapCodes and its initialization as static so I only have 1 instance populated once?

    I was looking into doing something like using a STATIC CLASS or STATIC STRUCT but couldn't seem to get it to work - when doing some reading a lot of people were saying that c++ doesn't really support STATIC CLASSES...

    Any help would be much appreciated...
    Thanks,

  • #2
    Rockstar Coder
    Join Date
    Jun 2002
    Location
    USA
    Posts
    9,074
    Thanks
    1
    Thanked 328 Times in 324 Posts
    Check the size of the map in the constructor and only load the data when the size is zero.
    OracleGuy


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •