Initialize class fields in constructor or at declaration?

前端 未结 15 2141
南旧
南旧 2020-11-22 01:16

I\'ve been programming in C# and Java recently and I am curious where the best place is to initialize my class fields.

Should I do it at declaration?:



        
15条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 01:58

    What if I told you, it depends?

    I in general initialize everything and do it in a consistent way. Yes it's overly explicit but it's also a little easier to maintain.

    If we are worried about performance, well then I initialize only what has to be done and place it in the areas it gives the most bang for the buck.

    In a real time system, I question if I even need the variable or constant at all.

    And in C++ I often do next to no initialization in either place and move it into an Init() function. Why? Well, in C++ if you're initializing something that can throw an exception during object construction you open yourself to memory leaks.

提交回复
热议问题