简体   繁体   中英

how do i initialize a class' private member static map whose value is a struct?

I have a class whose private member is a static map:

Class Devices
{   
    ...
    private:
    struct DevicePair
    {
       int nCtr;
       bool isToAdd;
    };
    DevicePair m_DevPair;
    static map <string, DevicePair> m_SYSdeviceMap;    
};

Why can't I just do this in the cpp file?

map <string, DevicePair> Devices::m_SYSdeviceMap;

How do I initialize this in the cpp file?

With this line:

map<string, Devices::DevicePair> Devices::m_SYSdeviceMap;

Also, as a good coding practice, remove the using namespace std; from your header, and qualify your use of map - std::map .

You cannot use the declaration you have said because it doesn't know what DevicePair is at that scope, you must be Devices:: before it

private statics are usually a bad idea by the way, you are usually better off having this instance hidden away in the "anonymous namespace" section in the .cpp file where it is visible to the functions in the compilation unit (usually the class members) but not external files.

The reason is that it is an implementation detail that you are exposing to all users of your class.

In your case that will be hard to do as DevicePair is private in your class and you cannot simply move that because it is needed in the header for m_DevPair.

Of course if you need your class to be thread-safe you need a mutex, etc. to control the accesses to the map (unless it is all initialised in one thread and then only read by multiple threads). The mutex would well of course be in your anonymous namespace (and almost certainly should be).

I would still re-think your design though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM