V在C++中,成员函数内部声明的statics的可见性是什么

VWhat is the visibility of statics declared inside a member function in C++?

本文关键字:声明 statics 可见性 是什么 内部 函数 C++ 成员      更新时间:2024-04-28

所以我理解:

class Foo {
public:
static int bar;
}

意味着我可以在任何地方或多或少地访问Foo::bar

但是像这样的代码呢?

class Foo {
public:
static int* bar() {
static int fred = 1;
static int barney = 2;
static int thelma = 3;
return &thelma;
}
};

如何访问fredbarney?我知道它们只创建过一次,并且在程序的整个生命周期中都存在,但据推测,它们不能作为Foo::barney访问。

我在实际代码中看到了这种模式,所以想知道它是如何工作的。

C++中有两个重要的概念:变量的可见性和生存期。

如何访问fred和barney?我知道它们只创建过一次,并且在程序的整个生命周期中都存在,但据推测,它们不能作为Foo::barney访问。

您无法访问它们(至少不能通过它们的名称访问,因为编译器无法链接它们,因为它们没有链接(。成员函数内的静态变量仅在函数内具有可见性程序的生存期(确切地说,它从程序流第一次遇到声明时开始,到程序终止时结束(和内部链接。

CCD_ 5变量用于单例设计模式。由于它们的可见性有限,但程序的生存期有限,所以您可以通过这种方式访问成员函数之外的静态变量。

class A {
public:
A& getInstance()
{
static A self;
return self;
}
A(const A&) = delete;
A& operator=(const A&) = delete;
private:
A();
};