类将指向其实例的指针作为私有成员的原因是什么
What is the reason behind a class holding a pointer to its instance as a private member?
我不知道这个概念是否有名字。我有一份班级申报单;
class A
{
public:
...
private:
static A* me;
}
- 这是一种模式吗
- 为什么会有人这么做
如果没有更多的代码来诊断意图,它看起来很像Singleton模式的实现。
stackoverflow和维基百科上有很多参考资料;
- https://en.wikipedia.org/?title=Singleton_pattern
- C++Singleton设计模式
您会发现可能有一些"get instance"方法或friend factory方法的实现。
class A {
public:
static A* getInstance();
// or
friend A* getInstance();
private:
static A* me;
};
为什么要这样做?引用维基百科
在软件工程中,singleton模式是一种将类的实例化限制为一个对象的设计模式。
我以前在Singletons
中见过这种情况。
singleton是一个在内存中只能存在一次的对象。为了实现这一点,你可以通过访问器"隐藏"它的构造函数并公开它的实例(比如getInstance()
)。这就是为什么它保留一个指向自己的私有指针。
其思想是,每当有人调用getInstance()
时,您都会返回指向静态实例的指针。这样可以确保类只有一个实例。
关于Singleton的教程可以在这里找到
单独使用没有任何意义。然而,如果与static A& getInstance()
函数结合,它看起来更像Singleton模式。
Singleton模式基本上是一种只创建该类的一个实例的方法,该实例在程序中随处使用。
不过,我更喜欢用另一种方式来实现这个模式。除了个人偏好之外,没有特别的理由使用这种实现方式。
class A{
private:
class A(){} //To make sure it can only be constructed inside the class.
class A(const A&) = delete;
class A(A&&) = delete; //To make sure that it cannot be moved or copied
public:
static A& getInstance(){
static A inst; //That's the only place the constructor is called.
return inst;
}
};
希望能有所帮助。
相关文章:
- int数据类型的指针指向的是什么,如果是一个类的私有数据成员,我们创建了该类的两个对象?
- 重载运算符的范围是什么?它是否会影响作为类成员的集合的插入函数?
- Visual C++: MSVC vs. GCC+CLANG: 处理 lambda 捕获类成员变量,正确的方法是什么?
- 指针类型类成员的动态强制转换的恒定性是什么?
- 删除类成员的动态分配内存的最佳方法是什么
- 初始化类成员的更好做法是什么?
- 键入擦除成员函数指针的"right"方法是什么?
- 使用只有一个成员的工会的目的是什么?
- C++:允许临时对象调用非常量成员函数的设计理念是什么?
- 命名空间 Win 没有成员"simpleControl"是什么意思
- 在多个对象中初始化预定义成员变量的正确方法是什么?
- 在不编写显式 setter 的情况下修改私有类数据成员的便捷方法是什么?模板有用吗?
- 这个星号 (*) 符号在 C++ 中是什么意思?-- 指向成员的指针
- 在单一实例类中将成员指针设置为 null 的正确方法是什么
- 返回没有 typedef 的成员函数指针的语法是什么?
- 使用静态类成员而不是私有字段之间的速度差异是什么?
- 使用泛型成员变量"placement new"结构/类数组的正确方法是什么?
- 从C++与 C 灵活阵列成员互操作的正确方法是什么?
- 删除数组成员的更好方法是什么?
- 显式初始化成员是什么意思