Home > front end >  Call count of static variable initialization inside static functions & methods
Call count of static variable initialization inside static functions & methods

Time:01-06

I have counter.h:

static int count() {
    static int counter = 0; // called anew in each translation unit
    return counter;
}

and Singleton.h:

class Singleton
{
public:
    Singleton(const Singleton& other) = delete;
    Singleton& operator = (const Singleton& other) = delete;

    static Singleton& instance()
    {
        static Singleton ret; // called only once
        return ret;
    }

private:
    Singleton() { std::cout << "call\n"; }
};

and foo.cpp:

void foo()
{
    count();
    auto& db = Singleton::instance();
}

zoo.cpp:

void zoo()
{
    count();
    auto& db = Singleton::instance();
}

main.cpp:

int main()
{
    foo();
    zoo();

    return 0;
}

Why the line static int counter = 0; called twice but the line static Singleton ret; only once?

CodePudding user response:

The function int count() is declared static, as such it gets internal linkage, meaning there's a separate copy of the function created in each translation unit in which it is used.

If you want a single count() function in the application, don't declare it static so that it gets external linkage (and move the definition to a .cpp file), or simply declare it inline.

inline int count() {
    static int counter = 0;
    return counter;
}

This is different from a static class member. Class members, including static ones, get the same linkage as the class they belong to (which in your case has external linkage).

  •  Tags:  
  • c
  • Related