c++:单例?如何向构造函数传递参数

C++: Singleton? How to pass arguments to the construtors?

本文关键字:构造函数 参数 单例 c++      更新时间:2023-10-16

我正在阅读"Effective c++ "中的第47项。在书中建议,所谓的非局部静态对象应该特别小心使用。相反,它建议使用如下内容:

Directory& tempDir()  
{  
         static Directory td;  
         return td;  
} 

我不确定它是否应该被称为单例。但是,我正在考虑如何将参数传递给类Directory的构造函数。例如,我想将路径作为字符串传递给目录td,也许我需要这样做:

Directory& tempDir(std::string & str)  
{  
         static Directory td(str);  
         return td;  
} 

问题是,每当我想访问目录td时,我必须传递字符串作为输入参数。这不是很漂亮。

有没有更优雅的方法?

谢谢。

有没有更优雅的方法?

不要在函数中传递路径,而是写一个全局函数来"生成"路径:

char const* get_path()
{
    // do_stuff and return the path
}
Directory& tempDir()  
{  
         static Directory td(get_path());  
         return td;  
} 

更好的方法是不使用单例。在main() -函数中创建对象,在那里初始化它,并通过引用传递给所有组件。

如果这对您的用例有帮助,您当然可以使用默认参数值,如Directory& tempDir(const std::string & str = "")

这是无稽之谈。每次调用这个函数时创建一个临时对象是完全没有必要的开销。

我假设您希望初始化全局实例,但然后将其作为单例访问。

你可以这样做:

class Directory
{ 
public: 
    Directory& tempDir(const std::string & str)
    {
        if (tempDir_ == nullptr)
        {
            tempDir_ = new Directory(str);
        }
        return *tempDir_;
    }
    Directory& tempDir()
    {
        assert(tempDir_);
        // Or throw an execption etc.
        return *tempDir_;
    }
private:
    Directory(const std::string & str)
    {
        // etc.
    }
    static Directory* tempDir_;
};

显然,您需要确保初始化调用确实首先发生,或者重构方法。

另外,您可能更喜欢将tempDir(const std::string & str)更改为initialiseTempDir(const std::string & str)或诸如此类的

我的建议

保留tempDir的第一个版本。

Directory& tempDir()  
{  
   static Directory td;  
   return td;  
} 

增加Directory成员函数设置路径。当需要设置路径时,使用:

tempDir().setPath(path);

使用这种方法允许创建具有状态的单例。您可以使用类似的accessor和modifier函数获取和设置与单例关联的其他状态。