- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
是否可以使用参数定义 Meyer 的单例(如 this one)?
我知道 GOF 风格的单例(如 here )是可能的,
但我似乎无法让它与 Meyer 的单例一起工作:
// ...
public:
static S& getInstance()
{
static S instance; // no way to pass arguments here ...
return instance;
}
编辑:
我想要一个 Init
函数和多个 getInstance
。所以典型的用法是这样的:
S::Init(5, 6.4);
foo(S::getInstance());
bar(S::getInstance());
最佳答案
您可以只将初始化参数存储在静态中。示例:
class S {
public:
static void Init(int i)
{
i_ = i;
initialized_ = true;
}
static S& getInstance()
{
if (!initialized_) {
throw SomeException;
}
static S instance(i_);
return instance;
}
private:
S(int) { }
static int i_;
static bool initialized_;
};
请记住在实现 (.cpp
) 文件中实际定义静态:
int S::i_ = 0;
bool S::initialized_ = false;
显然,您也可以对这些使用 Meyer 单例,但由于它们是内置类型并且不依赖于其他数据,因此您不会真正获得太多。
关于带参数的 C++ Meyer 单例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60575118/
Meyers Singleton 是否适用于有动态库的场景? IE。一个定义单例的库,其他人使用它,每个都在自己的编译单元中? (我想这无关紧要,但具体架构是 OS X 上带有框架的应用程序) 我正在
我已经阅读了很多关于单例的文章,它们应该在什么时候使用,什么时候不应该使用,以及如何安全地实现它们。我正在用 C++11 编写,并且遇到了 Meyer 的单例延迟初始化实现,如 this questi
是否可以使用参数定义 Meyer 的单例(如 this one)? 我知道 GOF 风格的单例(如 here )是可能的, 但我似乎无法让它与 Meyer 的单例一起工作: // ... public
Meyer 的单例类蓝图在头文件 temp.h 中声明。如果 temp.h 包含在两个单独的 .cpp 文件中,那么每个文件都有自己的蓝图,并且静态的东西对其他模块(即 *.o 或 *.cpp)不可见
到以下代码: class C { public: static C& Instance() { static C c; return c; }
假设我有一个类: class C{ int x_; int y_; public: C(int x, int y): x_(x), y_(y){} }; 然后我想从一个字符串中添加结构,它
我的代码: template class Singleton { public: static T& instance() { static T obj; re
我继承了一些在 g++ 9 和 10 下编译良好的代码,但是当打开优化时,两个编译器都会出现运行时错误(也就是说,编译 -O0 有效,但编译 -Og 会给出来自 MMU 的运行时错误.) 问题是在一个
我过来了this question最近,对 Instance() 函数的实现产生了疑问: class Configuration { public: static Configuration*
上周有人指出我有一段代码是这样的: #include namespace NSTest { class SingletonClass { public: static SingletonCl
我有以下实现基本 Meyers 单调的代码: #ifndef _cConfigFile_HH #define _cConfigFile_HH class cConfigFile { public:
Singleton(Meyers 的 Singleton)的以下使用惰性初始化的实现是否线程安全? static Singleton& instance() { static Singlet
我有一个在 Meyers 单例中运行的 boost 线程。它在我的程序期间愉快地运行。 当我的 Singleton 的析构函数被调用时(当程序加载出内存时)我设置了一个标志以便线程应该退出它的循环并触
Singleton(Meyers 的 Singleton)的以下使用惰性初始化的实现是否线程安全? static Singleton& instance() { static Singlet
我正在阅读 S. Meyers 的书“Effective C++。55 specific ways...”(第 3 版)。这本书中的某些内容,在规则 11 中,我不明白。所以,在下一个代码部分: Wi
我正在关注 Item6,它是 Scott Meyers 着的 Effective STL: 50 Specific Ways to Improve Your Use of the Standard T
我只是尝试使用 Scott Meyers 在“Effectice C++ in an Embedded Environment”中建议的 placement new 运算符。 DefaultM
我正在阅读 std::shared_ptr在Effective Modern C++14 Scott Meyers 的书。这是一段代码,作者说其中可能存在资源泄漏: int computePriori
Singleton(Meyers 的 Singleton)线程的以下使用延迟初始化的实现是否安全? static Singleton& instance() { static Singlet
所以我读了很多关于为什么这个实现不是线程安全的。但是我没有找到如何使其线程安全快速的答案?使其线程安全的变体是添加互斥体(或者在某些情况下,只需关键部分就足够了),但这会使该方法慢得多。那么是否有一种
我是一名优秀的程序员,十分优秀!