What is the rationale for not having static constructor in C++?

后端 未结 5 1533
长情又很酷
长情又很酷 2020-12-24 12:38

What is the rationale for not having static constructor in C++?

If it were allowed, we would be initializing all the static members in it, at one place in a very org

5条回答
  •  一向
    一向 (楼主)
    2020-12-24 12:49

    Using the static initialization order problem as an excuse to not introducing this feature to the language is and always has been a matter of status quo - it wasn't introduced because it wasn't introduced and people keep thinking that initialization order was a reason not to introduce it, even if the order problem has a simple and very straightforward solution.

    Initialization order, if people would have really wanted to tackle the problem, they would have had a very simple and straightforward solution:

    //called before main()
    
    int static_main() {
    
    ClassFoo();
    ClassBar();
    
    }
    

    with appropriate declarations:

    class ClassFoo {
     static int y;
      ClassFoo() {
       y = 1;
      }
    }
    
    class ClassBar {
      static int x;
      ClassBar() {
       x = ClassFoo::y+1;
      }
    }
    

    So the answer is, there is no reason it isn't there, at least not a technical one.

提交回复
热议问题