The static keyword and its various uses in C++

后端 未结 9 1581
自闭症患者
自闭症患者 2020-11-22 02:07

The keyword static is one which has several meanings in C++ that I find very confusing and I can never bend my mind around how its actually supposed to work.

9条回答
  •  别跟我提以往
    2020-11-22 03:07

    Variables:

    static variables exist for the "lifetime" of the translation unit that it's defined in, and:

    • If it's in a namespace scope (i.e. outside of functions and classes), then it can't be accessed from any other translation unit. This is known as "internal linkage" or "static storage duration". (Don't do this in headers except for constexpr. Anything else, and you end up with a separate variable in each translation unit, which is crazy confusing)
    • If it's a variable in a function, it can't be accessed from outside of the function, just like any other local variable. (this is the local they mentioned)
    • class members have no restricted scope due to static, but can be addressed from the class as well as an instance (like std::string::npos). [Note: you can declare static members in a class, but they should usually still be defined in a translation unit (cpp file), and as such, there's only one per class]

    locations as code:

    static std::string namespaceScope = "Hello";
    void foo() {
        static std::string functionScope= "World";
    }
    struct A {
       static std::string classScope = "!";
    };
    

    Before any function in a translation unit is executed (possibly after main began execution), the variables with static storage duration (namespace scope) in that translation unit will be "constant initialized" (to constexpr where possible, or zero otherwise), and then non-locals are "dynamically initialized" properly in the order they are defined in the translation unit (for things like std::string="HI"; that aren't constexpr). Finally, function-local statics will be initialized the first time execution "reaches" the line where they are declared. All static variables all destroyed in the reverse order of initialization.

    The easiest way to get all this right is to make all static variables that are not constexpr initialized into function static locals, which makes sure all of your statics/globals are initialized properly when you try to use them no matter what, thus preventing the static initialization order fiasco.

    T& get_global() {
        static T global = initial_value();
        return global;
    }
    

    Be careful, because when the spec says namespace-scope variables have "static storage duration" by default, they mean the "lifetime of the translation unit" bit, but that does not mean it can't be accessed outside of the file.

    Functions

    Significantly more straightforward, static is often used as a class member function, and only very rarely used for a free-standing function.

    A static member function differs from a regular member function in that it can be called without an instance of a class, and since it has no instance, it cannot access non-static members of the class. Static variables are useful when you want to have a function for a class that definitely absolutely does not refer to any instance members, or for managing static member variables.

    struct A {
        A() {++A_count;}
        A(const A&) {++A_count;}
        A(A&&) {++A_count;}
        ~A() {--A_count;}
    
        static int get_count() {return A_count;}
    private:
        static int A_count;
    }
    
    int main() {
        A var;
    
        int c0 = var.get_count(); //some compilers give a warning, but it's ok.
        int c1 = A::get_count(); //normal way
    }
    

    A static free-function means that the function will not be referred to by any other translation unit, and thus the linker can ignore it entirely. This has a small number of purposes:

    • Can be used in a cpp file to guarantee that the function is never used from any other file.
    • Can be put in a header and every file will have it's own copy of the function. Not useful, since inline does pretty much the same thing.
    • Speeds up link time by reducing work
    • Can put a function with the same name in each translation unit, and they can all do different things. For instance, you could put a static void log(const char*) {} in each cpp file, and they could each all log in a different way.

提交回复
热议问题