davidhood2
davidhood2

Reputation: 1367

Singleton Pattern Object with Parameters

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.

Sensors.h

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 ;"
};

Sensors.cpp

#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!

Upvotes: 6

Views: 3705

Answers (1)

Ashot
Ashot

Reputation: 10979

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.

Upvotes: 7

Related Questions