具有可变成员的单例对象

发布于 2024-12-12 16:24:10 字数 858 浏览 2 评论 0原文

编辑:请参阅 GWW 的答案,问题只是使用 C::Instance() 进行非法复制。我错了,错误不依赖于可变的。

静态方法与可变方法不兼容吗?这是我的代码的简化版本:

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();

然后我得到的错误(gcc 4.2)是

错误:“QMutex::QMutex(const QMutex&)”在此上下文中是私有的

此处首先需要合成方法“C::C(const C&)” //at C::Instance()

如果我删除 'mutable'关键字这个错误消失了,但是我当然不能使锁定/解锁 _mutex const 的方法。编写我自己的 copyctor 不会改变任何东西。有人知道如何解决这个问题吗?注意,这看起来与 这篇文章 类似,但那是 Objective-C,而且只是那里有太多代码似乎与问题无关。

编辑:刚刚意识到问题显然是 QMutex 的复制构造函数是私有的。但我不明白为什么“可变”应该在这里产生影响,即为什么它会产生副本。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

冬天的雪花 2024-12-19 16:24:10

您试图复制您的单例,但它失败了,因为您已将复制构造函数声明为私有。它与可变成员完全无关。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文