declaration

C# member variable initialization; best practice?

若如初见. 提交于 2019-11-25 21:35:53
Is it better to initialize class member variables on declaration private List<Thing> _things = new List<Thing>(); private int _arb = 99; or in the default constructor? private List<Thing> _things; private int _arb; public TheClass() { _things = new List<Thing>(); _arb = 99; } Is it simply a matter of style or are there performance trade-offs, one way or the other? In terms of performance, there is no real difference; field initializers are implemented as constructor logic. The only difference is that field initializers happen before any "base"/"this" constructor. The constructor approach can

Defining static const integer members in class definition

ⅰ亾dé卋堺 提交于 2019-11-25 21:07:41
My understanding is that C++ allows static const members to be defined inside a class so long as it's an integer type. Why, then, does the following code give me a linker error? #include <algorithm> #include <iostream> class test { public: static const int N = 10; }; int main() { std::cout << test::N << "\n"; std::min(9, test::N); } The error I get is: test.cpp:(.text+0x130): undefined reference to `test::N' collect2: ld returned 1 exit status Interestingly, if I comment out the call to std::min, the code compiles and links just fine (even though test::N is also referenced on the previous line

Variable declaration placement in C

北战南征 提交于 2019-11-25 18:53:12
I long thought that in C, all variables had to be declared at the beginning of the function. I know that in C99, the rules are the same as in C++, but what are the variable declaration placement rules for C89/ANSI C? The following code compiles successfully with gcc -std=c89 and gcc -ansi : #include <stdio.h> int main() { int i; for (i = 0; i < 10; i++) { char c = (i % 95) + 32; printf("%i: %c\n", i, c); char *s; s = "some string"; puts(s); } return 0; } Shouldn't the declarations of c and s cause an error in C89/ANSI mode? It compiles successfully because GCC allows it as a GNU extension,