Re: Trouble finding information in C++ standard
Joe wrote:
James Kanze wrote:
If you use a variable, it must be initialized. And if you don't
use it, there's no need to even define it.
Hmmmm, I think the standard problem here is trying not to double
initialize.
Yes. I think I expressed myself poorly. If you use a variable,
it must be initialized (I'm using initialized in the everyday
sense here, not in the very restricted sense it is used in the
C++ standard), but that initialization needn't take place in the
same translation unit.
For example, some api's require:
unsigned int resourceLength;
GetResourceLength(MY_RESOURCE, &resourceLength);
.... // use resourceLength down here
Now, in general, I am usually willing to pay for an intialization upon
declaration, but I can see where some may not.
I was definitely considering things like:
int i ;
if ( cond )
i = 1 ;
else
i = 2 ;
I would expect any modern compiler to be able to recognize that
i has been explicitly initialized by the programmer, and not
generate any additional initialization for it.
When the actual initialization occurs in the function, there are
really very few cases where the compiler cannot detect this.
The problem only occurs when the variable is passed as a pure
out parameter, i.e. the called function initializes it, and
doesn't expect any particular previous initialization. C++
doesn't support out parameters---if the parameter were a class
type, an out parameter would mean passing the address of
uninitialized memory of the correct size and alignment
(something you cannot even declare).
As it happens, in all of the real cases I know of, the called
function takes enough time (and the out parameter is small
enough) that the initialization can make no measurable
difference. (It's easy to construct artificial cases where this
is not the case, of course. But do they occur in practice?)
I suppose in the ideal
world, GetResouceLength() would return the info and throw on error, but
most OS's don't use throwing to report errors.
Most OS's use a C interface for their API, for a variety of
reasons. There's no conceptual problem (at least in my mind)
with out parameters, but C++ really doesn't have any support for
them (and C is of such a low level that the distinction is
irrelevant).
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orientie objet/
Beratung in objektorientierter Datenverarbeitung
9 place Simard, 78210 St.-Cyr-l'Icole, France, +33 (0)1 30 23 00 34
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]