18 points · by ikalnitsky · 12y ago · 31 comments
No you don't. You are free to define a constructor that leaves some fields as garbage; in fact that's the default behavior.
This is about a bad language that force GOOD developers to figth against it.
"Always use memset onto struct variable before usage, because by default it's filled with garbage."
See? The language PUT GARBAGE on your code. Good or bad developer, not matter.
Now, a more experienced developer will remember that it need to correct the problems the language force on ALL the users.
Not all the blame is in the people. Somethings, the tools are at fault, too..
It didn't put it there. It just allocated some memory. Not more, not less. If you, for example, malloc a large chunk of memory but don't intend to use it sequentially or not right away, you can save time by not memset'ing it to zero, which would be pointless. C gives you the liberty to defer the initialization, but if you're careless, you'll shoot yourself in the foot. It's very much like having a car with manual vs. automatic transmission. More power = more responsibility. If you need power, you have to accept some compromises, and in this case, the compromise is that you need to mind what's in your memory all the time.
The fact that they didn't tells me that this was a conscious decision, not some "Legacy C" cruft that's left there for the sake of backward compatibility. And indeed the core tenet of C++ is "You only pay for what you use", isn't it? Zero-initializing a struct would be against C++'s philosophy.
template <class C> SPL_INLINE_FORCE void Zero(C &c) { memset(&c, 0, sizeof(c)); }
struct tm tm_struct;
Zero(tm_struct);
struct tm tm_struct = { 0, }; struct tm tm_struct = { }; struct foo { char bar[3]; };
These declarations are equivalent: struct foo f1 = { 0, };
struct foo f2 = { { 0, } };He didn't initialize a struct properly, results in errors...
Conclusion: C is evil?