不允许定义类的多个实例
Disallow defining more than one instance of a class
虽然以前我读到不允许定义一个对象的进一步实例。但我再也找不到那篇文章了。谁能告诉我如何防止从类CLog
定义任何其他对象?
class CLog
{
........
} log;
单例的另一种解决方案是使用 Service Locator
模式。
http://gameprogrammingpatterns.com/service-locator.html 中描述了对它的良好描述以及如何使用它。
同样,像单例一样,这种模式应该谨慎使用,但是日志记录系统可能是一个很好的用例,如果没有别的,它会教你一些新的设计模式。
将构造函数设为私有。定义一个返回类实例的公共方法。
class sample{
private:
sample(){};
static *sample instance;
public:
static *sample getInstance(){
if (instance != null)
instance = new sample();
return instance;
}
getInstance() 方法在创建之前创建类实例,它会检查该实例是否存在,如果存在,它会重新调整现有的实例,否则会创建一个新的实例。通过这种方式,您可以使类创建类的单个实例。由于构造函数是私有的,因此没有人可以使用构造函数创建对象。
相关文章:
- 对显式实例化的模板函数的未定义引用
- 未定义的类模板不会实例化以检查友元函数
- 将自定义 QMap 模板实例化以人类可读的形式保存在 QSettings 中
- OSX clang++:用于 cpp 文件中显式实例化模板的体系结构x86_64的未定义符号
- "extern"声明以及带有和不带参数列表的类模板实例的后续定义
- 何时需要实例化函数模板定义?
- 使用用户定义的类型 UDT 实例化 std::atomic<>。如果 UDT 具有虚函数,则 l 墨水将失败。为什么?
- 实例化具有不完整类型的类模板格式不正确(如果该类型是在之后定义的)
- 将类成员函数的模板定义放在 CPP 文件中C++隐式实例化而不是 .H 允许吗?
- C++ 为什么在定义的编译和链接之前引用外部实例的程序
- 有没有办法根据命令行参数定义数组大小?运行时与编译时实例化?
- 如何使用自定义流操纵器在类实例中保存数据
- 是否是从等待返回到悬而未决的"this"实例的未定义行为?
- XCode 警告"此处需要实例化变量'Singleton:<Foo>:_instance',但没有可用的定义
- 为什么c++允许成员函数定义中实例的私有成员访问
- 即使我正在.cpp文件中实例化一个伪对象,.cpp文件内模板函数的定义也不起作用
- C++:如何在结构中定义类实例.类具有参数化的构造函数
- 自定义链表const_iterator无法遍历列表的非const实例
- 每个类实例的自定义函数 (C++)
- 下面哪些c++内置操作是为类实例定义的?