Search code examples
c++staticsingletonmutable

Singleton objects with mutable members


EDIT: See GWW's answer, the problem was simply making an illicit copy with C::Instance(). And I was wrong, the error does not depend on mutable.

Are static methods incompatible with mutable methods? Here's a simplified version of my code:

c.h:

class C 
{
    public:
        static C& Instance();
    private:
        C();

        mutable QMutex _mutex; 
};

c.cpp:

C& C::Instance() 
{
    static C instance;
    return instance; 
} 
C c = C::Instance();

Then the error I'm getting (gcc 4.2) is

error: 'QMutex::QMutex(const QMutex&)' is private within this context

synthesized method 'C::C(const C&)' first required here //at C::Instance()

If I remove the 'mutable' keyword this error goes away, but then of course I can't make the methods that lock/unlock _mutex const. Writing my own copy ctor doesn't change anything. Anyone know how to solve this? NB this looks similar to this post but that's objective-C and there was just too much code in there that didn't seem relevant to the question.

EDIT: Just realized that the problem, obviously, is that QMutex's copy ctor is private. But I don't understand why 'mutable' should make a difference here, i.e. why it induces a copy.


Solution

  • You are trying to copy your singleton and it fails because you have declared a copy constructor private. It has absolutely nothing to do with mutable members.