【发布时间】:2019-05-26 04:54:21
【问题描述】:
我希望这是一个连贯的问题...我有一个单例类定义,例如:
#include A.h
class Singleton
{
public:
// If I change this to a return by pointer, it works fine. But reference gives me problems.
static Singleton &getInstance();
Singleton(Singleton const&) = delete;
void operator=(Singleton const&) = delete;
~Singleton();
friend void A::friendMethodinA();
private:
Singleton();
void methodOnlyNeededByA();
}
类定义为:
Singleton &Singleton::getInstance()
{
static Singleton instance;
return instance;
}
Singleton::~Singleton() {}
Singleton::Singleton() {}
void Singleton::methodOnlyNeededByA() { // method body. }
我的 A 类声明是:
#pragma once
class Singleton;
class A
{
public:
void friendMethodinA();
private:
// This is what I'm not sure about. I tried
// Singleton &mSingleton = Singleton::getInstance(); This gives me "use of undefined type 'Singleton'" error. I can't #include Singleton.h because of the friend function.
// Singleton mSingleton = Singleton::getInstance(); This gives me "cannot be reference -- it is a deleted function" error.
Singleton mSingleton; // This gives me "A::mSingleton uses undefined class 'Singleton'" error.
}
我真的很想通过引用而不是指针 b 来返回单例,以避免每次使用它时进行空检查和取消引用指针。有没有办法在不完全重构以避免使用友元函数的情况下实现这一点?
这个友元函数的用途是方法methodOnlyNeededByA()。由于它只需要由 A 类调用,我不想将它放在 Singleton 的公共接口中。
【问题讨论】:
-
“我真的很想通过引用而不是指针返回单例” - 您提供的代码已经通过引用而不是指针返回单例。
-
@Galik 是的,但是这段代码无法编译。正如我在 inline cmets 中提到的那样,我得到了编译器错误。我在 A 类中尝试的赋值操作均无效。
-
您是否尝试过此问题顶部答案中的代码? stackoverflow.com/questions/1008019/c-singleton-design-pattern
-
@Galik 是的,我的单例实现就是这样。访问单例的私有成员函数的朋友函数给我带来了问题。
-
class Singleton;的前向声明没有包含足够的关于Singleton的信息来实例化一个。此时所有A可以知道的是Singleton存在。它不知道Singleton的任何方法,所以你不能在这里调用它们。由于循环引用,您不能包含 Singleton.h,而 R Sahu 从那里获取它,所以我没有提交我的答案。
标签: c++ c++11 return singleton friend-function