【问题标题】:Singleton Pattern Object with Parameters带参数的单例模式对象
【发布时间】:2015-04-18 15:17:00
【问题描述】:

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

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

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

我已经把收到的错误代码放在了cmets中。

此外,我正在 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::Instance(foo, bar).doSomething(); Sensors::Instance(baz, qux).doSomething();。第二次调用将公然忽略参数,这在调用站点根本不明显。
  • 这很重要吗?由于它不应该创建新对象而是返回原始对象,因此忽略参数是否重要?如果要检查参数,在返回原始对象之前在方法中添加验证步骤不是很简单吗?
  • 问题是它们在代码中不会很好地相互跟随。假设您在代码中只看到Sensors::Instance(alpha, beta).doSomething(); somwhere。您无法知道该实例是否实际具有参数alphabeta,或者它是否会作用于在先前调用中创建的具有可能完全不同的参数的实例。

标签: c++ design-patterns reference singleton


【解决方案1】:

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

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

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

【讨论】:

  • 谢谢。我现在正在尝试这样创建对象: Sensors Sense = Sensors.Instance(p19, p20);但是,显然“main.cpp”中不允许使用类型名称 - 我如何实例化我的单例对象?再次感谢!
  • 你应该写Sensors& Sense = Sensors::Instance(p19, p20); 现在Sense 指的是单例对象。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-16
  • 2011-05-11
相关资源
最近更新 更多