[英]Function pointer static, constructor
In this code we have static class variable and i need someone to explain what happens here and how i can use it.It is a static class variable and a function that gets the variable with a reference.
class Constructor
{
private:
static Constructor constructor;
public:
static Constructor* constructor();
};
Constructor Constructor::constructor;
Constructor* constructor::constructor()
{
return &constructor;
}
一旦您删除错误以便它编译
class Constructor
{
private:
static Constructor constructor_;
public:
static Constructor* constructor();
};
Constructor Constructor::constructor_;
Constructor* Constructor::constructor()
{
return &constructor_;
}
您最终会在 static 变量Constructor::constructor_
中获得一个私有实例,该实例只能通过其 static 公共Constructor::constructor()
方法访问。 这种仅允许创建 class 的单个实例的构造类型称为 singleton。 它是这样使用的:
int main(){
auto* s1 = Constructor::constructor();
auto* s2 = Constructor::constructor();
std::cout << (s1 == s2);
}
在此处查看工作版本。
有关更多信息,请参阅Singleton 的线程安全初始化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.