I'm trying to create a C++ singleton pattern object, using references not pointers, where the constructor takes 2 parameters
I have looked at a whole host of example codes, including: Singleton pattern in C++, C++ Singleton design pattern and C++ Singleton design pattern
I believe I understand the principles involved, but despite attempting to lift snippets of code almost directly from the examples, I cannot get it to compile. Why not - and how do I create this singleton pattern object using a constructor that takes parameters?
I have put the errors received in the code comments.
Additionally, I am compiling this program in the ARMmbed online compiler - which may/may not have c++ 11, I am currently trying to find out which.
class Sensors
{
public:
static Sensors& Instance(PinName lPin, PinName rPin); //Singleton instance creator - needs parameters for constructor I assume
private:
Sensors(PinName lPin, PinName rPin); //Constructor with 2 object parameters
Sensors(Sensors const&) = delete; //"Expects ;" - possibly c++11 needed?
Sensors& operator= (Sensors const&) = delete; //"Expects ;"
};
#include "Sensors.h"
/**
* Constructor for sensor object - takes two object parameters
**/
Sensors::Sensors(PinName lPin, PinName rPin):lhs(lPin), rhs(rPin)
{
}
/**
* Static method to create single instance of Sensors
**/
Sensors& Sensors::Instance(PinName lPin, PinName rPin)
{
static Sensors& thisInstance(lPin, rPin); //Error: A reference of type "Sensors &" (not const-qualified) cannot be initialized with a value of type "PinName"
return thisInstance;
}
Thanks very much!
A parameter is assigned to the constructor of the singleton class type (as we did in step two). We initialize a public static getObject or getInstance function with a class object as the return value.
The singleton pattern is one of the simplest design patterns. Sometimes we need to have only one instance of our class for example a single DB connection shared by multiple objects as creating a separate DB connection for every object may be costly.
The singleton design pattern is one of the twenty-three well-known "Gang of Four" design patterns that describe how to solve recurring design problems to design flexible and reusable object-oriented software with the aim of making it easier to implement, change, test, and reuse objects.
It falls under the category of the creational design pattern in Java. A Singleton class in Java allows only one instance to be created and provides global access to all other classes through this single object or instance.
You should create static local variable, not a reference. Change to this.
Sensors& Sensors::Instance(PinName lPin, PinName rPin)
{
static Sensors thisInstance(lPin, rPin);
return thisInstance;
}
This will return the same object (created by first lPin
and rPin
) any time calling Sensors::Instance
method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With