c++:单例?如何向构造函数传递参数
C++: Singleton? How to pass arguments to the construtors?
我正在阅读"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函数获取和设置与单例关联的其他状态。
相关文章:
- 将成员函数作为构造函数参数调用时出错 "Variable is not a type name"
- 在按值调用 (c++) 中转发构造函数参数
- 如何使用 swig 修改类构造函数以保留对其中一个构造函数参数的引用?
- 如何在构造函数参数中初始化"std::set"?
- 何时应在构造函数参数中使用 const C++?
- 使用模板化结构作为构造函数参数
- 使用 lambda 作为构造函数参数是否需要C++ 17?
- 如何使输入文本文件成为构造函数参数?c++
- shared_ptr构造函数参数是否应按值传递
- 是否允许使用初始值设定项列表将const数组引用实例化为构造函数参数
- 复制构造函数参数为0
- 用作成员构造函数参数的函数的求值顺序
- 结构中的默认成员值或默认构造函数参数
- C++将引用成员绑定到构造函数参数
- 如何通过可变参数模板将多个构造函数参数转发到数组初始值设定项列表?
- 模板函数指针参数与构造函数参数
- 如何将 std::string 作为构造函数参数传递,并将其保存的 C 字符串存储在 void 指针中?
- 如何基于构造函数参数模板化类成员函数的代码
- 将派生类构造函数参数传递给受保护的成员
- 如何根据构造函数参数使用超类类型初始化成员变量?