c++ - 带参数的单例模式对象

标签 c++ design-patterns reference singleton

我正在尝试创建一个 C++ 单例模式对象,使用引用而不是指针,其中构造函数采用 2 个参数

我查看了大量示例代码,包括: Singleton pattern in C++ , C++ Singleton design patternC++ Singleton design pattern

我相信我理解所涉及的原则,但尽管试图几乎直接从示例中提取代码片段,但我无法编译它。为什么不——以及如何使用带参数的构造函数创建此单例模式对象?

我已将收到的错误放在代码注释中。

此外,我正在 ARMmbed 在线编译器中编译这个程序——它可能有/可能没有 c++ 11,我目前正试图找出是哪个。

传感器.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 ;"
};

传感器.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;
}

非常感谢!

最佳答案

您应该创建静态局部变量,而不是引用。改成这个。

Sensors& Sensors::Instance(PinName lPin, PinName rPin)
{
    static Sensors thisInstance(lPin, rPin);     
    return thisInstance;
}

这将在任何时候调用 Sensors::Instance 方法时返回相同的对象(由第一个 lPinrPin 创建)。

关于c++ - 带参数的单例模式对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29719175/

相关文章:

c++ - To::close() 还是 to::fclose()?

c++ - std::atomic_...<std::shared_ptr> 应该如何用于线程安全类的复制和移动操作?

c++ - 资源泄漏 : fExclfile

JavaScript 代码组织建议/代码审查

c++ - 在 ctor 中使用 const vector 初始化的 const vector 成员

c++ - 为什么我可以将引用作为参数传递给构造函数的指针参数?

c++ - 是否可以在 C++ 中执行此 lambda 事件管理器?

design-patterns - 你能在任何需要单例的地方使用依赖注入(inject)吗?

python - 在 Python 中使用闭包和动态定义的函数是一种自然的设计模式吗?

Python:为 "through"分配一个迭代器