samedi 25 mai 2019

What is the correct way to assign a singleton to a variable when returned by reference in C++?

I hope this is a coherent question... I have a singleton class definition like:

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

The class definition is:

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

Singleton::~Singleton() {}

Singleton::Singleton() {}

void Singleton::methodOnlyNeededByA() { // method body. }

My class A declaration is:

#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.
}

I would really like to return the singleton by reference rather than pointer bto avoid null checks and dereferencing the pointer every time I use it. Is there a way to achieve this without completely refactoring to avoid using friend functions?

The purpose of this friend function is the method methodOnlyNeededByA(). Since it only ever needs to be called by Class A, I do not want to put it in the public interface of the Singleton.

Aucun commentaire:

Enregistrer un commentaire