如何在单例中传递参数

Cha*_*hax 6 c++ singleton argument-passing

我一直想知道如何将参数传递给单例构造函数.我已经知道如何做一个单身人士,但我一直不幸找到办法.

这是我的代码(部分代码).

Questionnary* Questionnary::getInstance(){

    static Questionnary *questionnary = NULL;

    if(questionnary == NULL){
        cout << "Object created";
        questionnary = new Questionnary();

    }
    else if(questionnary != NULL){
        cout << "Object exist";
    }

    return questionnary;
}

Questionnary::Questionnary(){
    cout << "I am an object";
}

//This is want i want to acheive
Questionnary::Questionnary(string name){
    cout << "My name is << name;
}
Run Code Online (Sandbox Code Playgroud)

提前谢谢了

(顺便说一下,我知道单身人员是如何以及为什么不好)

Lih*_*ihO 5

您不需要动态分配单例实例.它可能看起来如下(这有时被称为"延迟加载单例"〜实例创建得晚,有点"自动"):

#include <iostream>
#include <string>

class Questionnary
{
private:
    // constructor taking string:
    Questionnary(const std::string& name) : name_(name) { }
public:
    static Questionnary& getInstance(const std::string& name)
    {
        static Questionnary q(name);
        std::cout << "My name is: " << q.name_ << std::endl;
        return q;
    }
private:
    std::string name_;
};

int main() {
    Questionnary::getInstance("Josh");
    Questionnary::getInstance("Harry");
}
Run Code Online (Sandbox Code Playgroud)

输出:

My name is: Josh
My name is: Josh
Run Code Online (Sandbox Code Playgroud)

请注意,构造函数只getInstance在第一次调用时才会被调用一次.

  • 如何在没有参数的情况下为此实现添加getInstance方法?(只是为了以后获取实例,而不需要传递参数) (3认同)
  • 我不明白为什么这是可接受的答案,因为它演示了如何“不”将参数传递给单例的构造函数。此外,即使除了第一个调用之外的所有参数都将被忽略时,仍然需要传递该参数,这是造成混乱的主要原因 (3认同)

neo*_*nxc 5

让我扩展一下Martin York对于您的用例的答案。我建议在这种特殊情况下使用指针作为参数,因为我们利用了它的固有属性,因此它可以是“空”的。

class Questionnary
{
  std::string _str;

  static Questionnary& getInstanceImpl(std::string* const s = nullptr)
  {
    static Questionnary instance{ s };
    return instance;
  }

  Questionnary(std::string* const s)
    : _str{ s ? move(*s) : std::string{} } // employ move ctor
  {
    if (nullptr == s)
      throw std::runtime_error{ "Questionnary not initialized" };
  }

public:
  static Questionnary& getInstance()
  {
    return getInstanceImpl();
  }
  static void init(std::string s) // enable moving in
  {
    getInstanceImpl(&s);
  }

  Questionnary(Questionnary const&) = delete;
  void operator=(Questionnary const&) = delete;
};
Run Code Online (Sandbox Code Playgroud)

我发现这种方法不太混乱,因为它让您在第一次初始化后就获得了实例,而没有(无论如何都丢弃了)参数:

// first init
Questionnary::init("my single Questionnary");

// later on ...
Questionnary& q = Questionnary::getInstance();
Run Code Online (Sandbox Code Playgroud)

编辑:从getInstance函数和一些优化中删除参数。