Something that has always bothered me is why isn't data set to NULL by the compiler, if nothing else was specified? I c开发者_如何转开发an't see any reason NOT to, and surely it must be better than the junk that gets referred to otherwise?
The original reason was "for speed" -- the variables were only going to make sense once you assigned something to them, so there was an effort to not make a pointless initialization to 0
that was just going to be overwritten by the programmer in a few milliseconds with the actual data anyway.
While it isn't exactly expensive, compilers probably don't zero out variables today for the same reason: any compiler that does would look slow compared to other compilers on benchmarks.
The only good reason is that it's not as efficient. C and C++ (unlike higher-level languages) tend not to do anything you didn't ask for. That is how they got the reputation of being extremely fast. Other languages are safer, but slower.
If you wanted to initialise fields to anything other than NULL, it would be a waste of time to first initialise it to NULL and then initialise it to whatever you set it to. So C/C++ assumes you know what you are doing.
My guess is because of speed reasons. They would be another CPU call(s) to do it.
Setting the allocated memory to zeroes and marking the structures as 'null' takes time. Your application may have time-critical sections where objects must be instantiated as quickly as possible, after which you initialise them in as minimalist way as possible to make them usable. So the compiler and runtimes do as little work as possible to make the objects, and leave it to you to complete their setup as you see fit.
Some high-level languages do implement further initialisation to 'null', but these are then not always suitable for time-critical applications.
If you declare a variable on the heap (not free store, i.e. globally and only globally), this will be initialised to 0.
Data on the stack, however, is not allocated as a way to speed this up. There's no point initialising data to 0 if you're going to overwrite it, which is the assumption made with local (stack) data.
精彩评论