Singleton pattern in C++

前端 未结 8 1835
北荒
北荒 2020-11-30 18:10

I have a question about the singleton pattern.

I saw two cases concerning the static member in the singleton class.

First it is an object, like this

8条回答
  •  心在旅途
    2020-11-30 18:28

    In response to the "memory leak" complaints, there is an easy fix:

    // dtor
    ~GlobalClass()
    {
        if (this == s_instance)
            s_instance = NULL;
    }
    

    In other words, give the class a destructor that de-initializes the hidden pointer variable when the singleton object is destructed at program termination time.

    Once you've done this, the two forms are practically identical. The only significant difference is that one returns a references to a hidden object while the other returns a pointer to it.

    Update

    As @BillyONeal points out, this won't work because the pointed-to object never gets deleted. Ouch.

    I hate to even think about it, but you could use atexit() to do the dirty work. Sheesh.

    Oh, well, never mind.

提交回复
热议问题