开发者

Callback into singleton class

I am using a singleton class with a thread that calls into the singleton. I was asked during a review why I used the this pointer instead of the singleton instance.

My code with the suggested changes.

class myClass : public threadWrapper
{
public:
    static myClass& instance()
    {
        static myClass instance;
        return instance;
    }

    // This is the callback that I have implemented
    static void callback(void *me)
    {
        if (me != NULL)
            static_cast<myClass*>(me)->doCallback();
    }

    // This is the suggested callback
    static void callback2(void *me)
    {
        instance().doCallback();
    }

    // caller gets instance and then calls initialise()
    int initialise()
    {  
        if (initialised)
            return ERROR_ALREADY_INITIALISED;

        // Initialise the class

        // my thread startup call
        // thread wrapper class initialisation that calls pthread_create that runs the callback method with this as a parameter
        // priority is a global value that difines the relative priority of the various threads.
        threadWrapper::Initialise(priority, callback, this);
        initialised = true;

    }
private:
    myClass() : initialised(false) {;}

    void doCallback(void);

    bool initialised;

    static const int 
}

So is there any significant difference in speed between the two?

The threadWrapper is mandated in the existing code base, and I'm not allowed to use boost.

My justification was that if 开发者_C百科we needed to make this not a singleton then fewer changes would be required.


The speed difference will be pretty much nonexistent.

As for code quality, Singletons are quite horrendous and I personally would chuck out both forms, especially in a threaded environment. Assuming that it's too late for that, however.

The thing is, if you're gonna pass in a pointer to the object, why not just not make that object global in the first place? And if you are, it should at least be strongly typed. And then, you're just ... wrapping a member method in a static method? Why bother? Anyone who has a pointer to the class can just call the method on it in the first place. This is just insane.

Edit: If you're stuck with the existing design, then the second version is definitely better than the first and no slower. Even if you have existing code that depends on the Singleton, then it's absolutely better to refactor what you can to not depend on it.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜