开发者

C++: duplicated static member?

I have a class which needs to be a singleton. It implemented using a static member pointer:

class MySinglton
{
public:
    static MySinglton& instance() { ... }
private:
    static MySinglton* m_inst;
};

This class is compiled into a .lib开发者_Python百科 which is used in multiple dlls in the same application. The problem is that each dll sees a different m_inst. since it is compiled and linked separatly.

What is simple way to solve this problem?

Separating the .lib to its own dll is not an option. it must be a .lib.


One way solving the problem is that creating a shared memory, and creating the object in the shared memory. The two modules still have two copies of the pointers, but they point to the same location i.e. same instance of an object.


A solution could be transferring the instantiation to the application, and the DLLs will get reference to it during initialization. It may not be as elegant as you'd like, but it would do it.

Need to know what's the REAL problem behind your question. The answer may not be in the form you expect it. ;)


I don't know if you consider this simple, but you'll need to allocate a "master instance" (on the heap, say) and then let all your MySingleton instances refer to the "master instance".


C++ has no built-in mechanism for sharing variables in the way you seem to want. The only solution is to pass the single instance as a function parameter, using a pointer or reference.


I would use the shared memory mechanism provided by your os, MapViewOfFile or shmem. This might go:

class MySinglton
{
    public:
        static MySinglton& instance() {
            static MySinglton* m_inst = get_shared();
            return *m_inst;
        }
    private:
        static MySinglton * get_shared()
        {
            //1. Try to open shared memory, handle = OpenFileMapping.
            //2. If successful, return MapViewOfFile(handle).
            //3. Else, allocate enough space using CreateFileMapping, sizeof(MySingleton).
            //4. Initialise MapViewOfFile(handle), return MapViewOfFile(handle).
        }

        void Initialise()
        {
            // Stuff you would normally do in operator new here.
        }

};


Not sure if it's the best way to do it... but I'll do it like that :
Build your singleton in a DLL itself, then add external methods:
- to init it
- to retrieve it.


There is no simple solution to your problem. Questions: If there is no solution shoosh what are you going to do? Abandon the project? Or re-structure it so the 'must be a .lib' constraint is removed? If this problem concerns a commercial project what are you going to say to the project manager, stakeholders, etc?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜