具有可变成员的单例对象
编辑:请参阅 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您试图复制您的单例,但它失败了,因为您已将复制构造函数声明为私有。它与可变成员完全无关。
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.