Click to See Complete Forum and Search --> : How to initialize static map?
szhang
June 26th, 2002, 01:47 PM
How can I initialize a static map type member without an instance?
For example:
class MyClass{
...
const static CMap<int,int,int,int> m_map;
}
const CMap<int,int,int,int> MyClass::m_map;
MyClass::m_map.SetAt(1,1); << Error
MyClass::m_map.SetAt(2,2); << Error
I need a static map (dictionary) in the class which is accessible by static function.
Thanks
jfaust
June 26th, 2002, 02:28 PM
Initialize it the first time the static method is called, as in:
static MyMap& getMap()
{
static bool firstCall = true;
if( firstCall )
{
firstCall = false;
// init map here
}
return m_map;
}
Jeff
proxima centaur
June 26th, 2002, 02:33 PM
user a static member method to get a reference to the map instance.
//static
CMap<int,int,int,int> & MyClass::getMap()
{
return m_map;
}
Btw, since this is a non-MFC forum, why don't you use the standard STL map?
:)
szhang
June 26th, 2002, 02:50 PM
Thanks for your good idea. It solves my problem.
Sonny :-)
sandodo
June 27th, 2002, 01:01 AM
const CMap<int,int,int,int> MyClass::m_map;
MyClass::m_map.SetAt(1,1); << Error
MyClass::m_map.SetAt(2,2); << Error
you declare that the m_map as const, can you modify it by SetAt()? That is the reason why return the reference of it by getMap() works since it removed the const implicitly. ;)
Anthony Mai
June 28th, 2002, 10:19 AM
None of previous follow ups is correct.
You can NOT modify any data that is declared as const. As a matter of fact, if memory storage is allocated for any const data, it will be put in a section of memory that is read-only, trying to write to that memory to change the data will cause a write protected memory exception.
You can cast to none-const pointer, return a reference, or do other "smart" thing to remove the constness, but the fact is the data is in write protected memory location so any attempt to modify them will fail.
Also what if your const CMap class stored hundreds of thousands of items. Do you manually code it to add all the items?
The only way of initializing a const class or structure, is to use the old C style way of initialize structures when declaring. Like this:
class MC
{
public:
int m_data1;
int m_data2;
};
const MC gMC = {1,2};
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.