Re: Unwanted Default Initialisation
Tom1s wrote:
The die was cast decades ago... but nonetheless I'd like to discuss:
Why do global objects and also, static objects in functions, get default
initialised?
We're given the choice with local variables, e.g.:
char s[65];
Versus:
char s[65] = {};
It'd be nice to have the choice with globals and statics in functions.
Just a thought.
I suppose you could circumvent the system:
template<class T>
class DoNotInit {
T object;
public:
DoNotInit() {}
/* Rather than:
DoNotInit() : object() {}
*/
T &operator()() { return object; }
};
void FuncInit()
{
static char s[65];
s[17] = '5';
};
void FuncDoNotInit()
{
static DoNotInit<char[65]> dni;
static char (&s)[65] = dni();
s[17] = '5';
}
With all of C's claims of efficiency, it looks like they dropped the ball
on this one.
(One thing I'll say about C++ though: If you have a problem with the
language, you can get around it most of the time.)
-Tom1s
Because space for global variables must be allocated in a program's
image - every global variable will be initialized with a specific value
at program startup. So in the interests of standardization, it makes
sense for all programs to initialize globals with the same, specific
value (0) instead of leaving each program to choose a specific value of
its own. There is certainly no incurred cost in terms of a program's
efficiency in zero-initializing global variables. Local variables, on
the other hand, re-use memory - so the initial value of a local
variable cannot be guaranteed without explicitly assigning it a value
upon allocation; so in the case of local variables, zero-initialization
would incur a cost.
In fact it is not possible to avoid zero-initialization for global
variables. The 65 character array in the static dni variable in the
sample program has in fact been zero-initialized - no differently than
had it been declared a global array on its own. In fact, in order to
initialize a global variable with random values, the program would have
to execute an initialization routine to do so explicitly. In other
words the default zero-initialization behavior is in fact the more
efficient behavior than the behavior which the DoNotInit class template
attempts to - but fails to - attain.
Greg
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html ]