1
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 asks us to replace non-local static variable with local static variable, but when we call FileSystem::theFileSystem().numDisks() multiple times, it will declare static FileSystem fileSystem multiple time which should not be good, right?

user7341005
  • 285
  • 1
  • 3
  • 13
  • 2
    `static FileSystem fileSystem` will exist only one time. – jkb Dec 08 '19 at 23:56
  • 1
    A local _non-static_ variable is created for every call of function (and destroyed when leaving the scope it is located in). For local `static` variables, it's completely different: They are created (and initialized) at latest when the function is entered the first time. Afterwards, the existing instance is re-used (and granted to be always the same). In this case, being local has a different valuable effect: It makes the variable "invisible" outside the function. – Scheff's Cat Dec 09 '19 at 07:50
  • 1
    Btw. the _They are created (and initialized) at latest when the function is entered the first time._ works even in multi-threading. That's what [Meyers Singleton](https://www.modernescpp.com/index.php/thread-safe-initialization-of-a-singleton#h3-1-meyers-singleton) is based on. – Scheff's Cat Dec 09 '19 at 07:55

1 Answers1

1

According to @jkb and @Scheff, local static variables only exist once and you can't declare non-local static variable twice.

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;
}
user7341005
  • 285
  • 1
  • 3
  • 13