The static keyword and its various uses in C++

后端 未结 9 1601
自闭症患者
自闭症患者 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 02:54

    What does it mean with local variable? Is that a function local variable?

    Yes - Non-global, such as a function local variable.

    Because there's also that when you declare a function local as static that it is only initialized once, the first time it enters this function.

    Right.

    It also only talks about storage duration with regards to class members, what about it being non instance specific, that's also a property of static no? Or is that storage duration?

    class R { static int a; }; // << static lives for the duration of the program
    

    that is to say, all instances of R share int R::a -- int R::a is never copied.

    Now what about the case with static and file scope?

    Effectively a global which has constructor/destructor where appropriate -- initialization is not deferred until access.

    How does static relate to the linkage of a variable?

    For a function local, it is external. Access: It's accessible to the function (unless of course, you return it).

    For a class, it is external. Access: Standard access specifiers apply (public, protected, private).

    static can also specify internal linkage, depending on where it's declared (file/namespace).

    This whole static keyword is downright confusing

    It has too many purposes in C++.

    can someone clarify the different uses for it English and also tell me when to initialize a static class member?

    It's automatically initialized before main if it's loaded and has a constructor. That might sound like a good thing, but initialization order is largely beyond your control, so complex initialization becomes very difficult to maintain, and you want to minimize this -- if you must have a static, then function local scales much better across libraries and projects. As far as data with static storage duration, you should try to minimize this design, particularly if mutable (global variables). Initialization 'time' also varies for a number of reasons -- the loader and kernel have some tricks to minimize memory footprints and defer initialization, depending on the data in question.

提交回复
热议问题