【问题标题】:Question about reading effective c++ item 4(replace non-local static variable with local static variable) [duplicate]关于阅读有效c ++项目4的问题(用局部静态变量替换非局部静态变量)[重复]
【发布时间】:2019-12-08 23:33:42
【问题描述】:
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();
...
}

The book要求我们用本地静态变量替换非本地静态变量,但是当我们多次调用FileSystem::theFileSystem().numDisks()时,它会多次声明static FileSystem fileSystem,这应该不是很好吧?

【问题讨论】:

  • static FileSystem fileSystem 只会存在一次。
  • 每次调用函数时都会创建一个局部非静态变量(并在离开它所在的范围时销毁)。对于本地static 变量,它完全不同:它们最迟在第一次进入函数时创建(并初始化)。之后,现有实例被重新使用(并被授予始终相同)。在这种情况下,本地化具有不同的有价值的效果:它使变量在函数之外“不可见”。
  • 顺便说一句。 它们最迟在第一次进入函数时被创建(和初始化)。甚至在多线程中也有效。这就是Meyers Singleton 的基础。

标签: c++


【解决方案1】:

根据@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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-18
    • 2012-08-24
    • 2015-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-02
    • 1970-01-01
    相关资源
    最近更新 更多