关于读取有效 c++ 第 4 项(将非局部静态变量替换为局部静态变量)的问题
Question about reading effective c++ item 4(replace non-local static variable with local static variable)
class FileSystem {
...
int numDisks();
...
};
FileSystem& theFileSystem() // this replaces the theFileSystem object
{
static FileSystem fileSystem; // define and initialize a local static object
return fileSystem;
}
class Directory {...};
Directory::Directory()
{
...
std::size_t disks = FileSystem::theFileSystem().numDisks();
...
}
书中要求我们用局部静态变量替换非局部静态变量,但是当我们多次调用FileSystem::theFileSystem().numDisks()
时,它会多次声明static FileSystem fileSystem
,这应该不好吧?
根据@jkb和@Scheff,局部静态变量只存在一次,不能两次声明非局部静态变量。
void test(){
static int i = 0;
i++;
cout<<i<<endl;
}
int main()
{
test(); // 1
test(); // 2
test(); // 3
static int j;
static int j; // error
return 0;
}
相关文章:
- 在 .h 文件中的类中声明静态变量和在.cpp文件中声明"global"变量有什么区别
- 模板基类中的静态变量
- 类和静态变量
- 不同作用域中的静态变量和全局变量
- 静态变量声明和定义
- 是否可以依赖函数范围的静态变量来执行程序关闭期间调用的方法?
- 在类中继承静态变量?
- "local scope"中的 C++ 初始化静态变量
- 使用静态变量的递归调用的不同输出
- 复制文件流C++静态变量
- 跨模板化函数编译的静态变量
- C++编译器是否优化了顺序静态变量读取?
- C++,每个循环初始化一个新的静态变量
- (为什么)我们可以在初始化中将非静态类成员分配给静态变量吗?
- 这些语句是否等效(静态变量、常量变量和泛型)
- 程序如何知道静态变量是否需要初始化?
- 类外的静态变量实例化
- 无法解析静态变量
- 函数局部静态变量:从性能角度来看的优点/缺点
- 访问从 CPP 文件到其他头文件的静态变量