从具有正向声明的类中向具有朋友功能的已声明单身类转发

swd*_*don 0 c++ singleton return friend-function c++11

我希望这是一个连贯的问题...我有一个单例类定义,例如:

#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();
}
Run Code Online (Sandbox Code Playgroud)

类的定义是:

Singleton &Singleton::getInstance()
{
   static Singleton instance;
   return instance;
}

Singleton::~Singleton() {}

Singleton::Singleton() {}

void Singleton::methodOnlyNeededByA() { // method body. }
Run Code Online (Sandbox Code Playgroud)

我的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.
}
Run Code Online (Sandbox Code Playgroud)

我真的很想通过引用而不是指针b来返回单例,以避免空检查和每次使用它时都取消对指针的引用。是否有一种无需完全重构即可避免使用好友功能的方法来实现这一目标?

这个朋友功能的目的就是方法methodOnlyNeededByA()。由于只需要A类调用它,因此我不想将其放在Singleton的公共接口中。

R S*_*ahu 5

您可以通过以下方法解决编译器错误:

  1. 使用引用类型作为成员变量。

    Singleton& mSingleton; 
    
    Run Code Online (Sandbox Code Playgroud)

    然后

  2. 在构造函数中初始化它。

但是,我要说明的更重要的一点是:不要使用type的成员变量Singleton。当您需要使用该类时,只需调用Singleton::getInstance()。您可以将对返回对象的引用存储在函数局部变量中,也可以仅使用返回的引用。

auto& ref = Singleton::getInsance();
ref.methodOnlyNeededByA();
Run Code Online (Sandbox Code Playgroud)

要么

Singleton::getInsance().methodOnlyNeededByA();
Run Code Online (Sandbox Code Playgroud)