class 将指向其实例的指针作为私有成员持有的原因是什么?
What is the reason behind a class holding a pointer to its instance as a private member?
不知道这个概念有没有名字。我有一个 class 声明;
class A
{
public:
...
private:
static A* me;
}
- 这是一种模式吗?
- 为什么会有人这样做?
我以前在 Singletons
看过这个。
单例是在内存中只能存在一次的对象。为此,您 'hide' 它的构造函数并将它的实例公开为访问器的方式(例如 getInstance()
对象的私有静态实例。这就是为什么它保留一个指向自身的私有指针。
想法是,每次调用 getInstance()
你 return 指向静态实例的指针。这样您就可以确保 Class.
只有一个实例
可以找到关于 Singleton 的教程here
没有更多代码来诊断意图,它看起来很像 单例模式.
的实现
在 Whosebug 和维基百科上有很多参考 material;
- https://en.wikipedia.org/?title=Singleton_pattern
- C++ Singleton design pattern
您会发现可能有一些 "get instance" 方法或朋友工厂方法的实现。
class A {
public:
static A* getInstance();
// or
friend A* getInstance();
private:
static A* me;
};
为什么要完成?引用维基百科
In software engineering, the singleton pattern is a design pattern that restricts the instantiation of a class to one object.
单独没有意义。但是,如果与 static A& getInstance()
函数结合使用,它看起来更像是单例模式。
单例模式基本上是一种只创建此 class 的一个实例的方法,该实例在程序中随处使用。
不过我更喜欢另一种实现此模式的方法。除了个人喜好之外,没有特别的理由使用这种实现方式。
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;
}
};
希望对您有所帮助。
不知道这个概念有没有名字。我有一个 class 声明;
class A
{
public:
...
private:
static A* me;
}
- 这是一种模式吗?
- 为什么会有人这样做?
我以前在 Singletons
看过这个。
单例是在内存中只能存在一次的对象。为此,您 'hide' 它的构造函数并将它的实例公开为访问器的方式(例如 getInstance()
对象的私有静态实例。这就是为什么它保留一个指向自身的私有指针。
想法是,每次调用 getInstance()
你 return 指向静态实例的指针。这样您就可以确保 Class.
可以找到关于 Singleton 的教程here
没有更多代码来诊断意图,它看起来很像 单例模式.
的实现在 Whosebug 和维基百科上有很多参考 material;
- https://en.wikipedia.org/?title=Singleton_pattern
- C++ Singleton design pattern
您会发现可能有一些 "get instance" 方法或朋友工厂方法的实现。
class A {
public:
static A* getInstance();
// or
friend A* getInstance();
private:
static A* me;
};
为什么要完成?引用维基百科
In software engineering, the singleton pattern is a design pattern that restricts the instantiation of a class to one object.
单独没有意义。但是,如果与 static A& getInstance()
函数结合使用,它看起来更像是单例模式。
单例模式基本上是一种只创建此 class 的一个实例的方法,该实例在程序中随处使用。
不过我更喜欢另一种实现此模式的方法。除了个人喜好之外,没有特别的理由使用这种实现方式。
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;
}
};
希望对您有所帮助。