david wrote:
Hello,
I'd like to know whether the compiler can detect a member variable which is
not initialized (on purpose) by the constructor.
Easier with an simple example (the class is supposed to be a fixed point
variable):
class A
{
private:
int my_value;
A (int init) { my_value = init; }
public:
A () {}
A (const A& init) { my_value = init.my_value; }
A& operator = (int scalar) { my_value = scalar << 8; }
...
};
int main (void)
{
int p, q;
A x, y;
p = q;
y = x;
}
The compiler complains about q beeing used but not initialized,
is there a way for it to complain about x too ?
(yes I could put 0 in the constructor, but code size is critical in the
embedded environment I use, and I'm curious too :-)
Thomas answered your question, but let me suggest that neither you nor
almost anyone knows enough about the language, the particular
compiler/optimizer, and the particular target systems to correctly
guess what will generate more code at this fine-grained level. But this
is not a bad thing. High-level languages exist to allow you to focus on
the high-level program, not the low-level details of your machine. On
the other hand, optimizers are usually quite good at figuring out what
will produce the smallest code (or the fastest code, depending on your
compiler switches), and you should use them to that end until
measurement -- not programmer intuition! -- tells you that you should
hand-optimize (probably in assembly).
Several examples:
1. You should generally use initialization rather than assignment when
possible. Your code above calls the constructor for x and y and then
calls the assignment operator for y, whereas it really only needed to
call the constructor for x and the copy constructor for y if you were
to declare and initialize y at the same point:
A y = x; // Or A y(x);
Maybe the optimizer will inline or get rid of the extra call, but maybe
not.
2. Initialization lists generally give better code for similar reasons.
In your trivial example above, it may not matter, but it certainly does
matter in lots of real circumstances
(
http://www.parashift.com/c++-faq-lit...html#faq-10.6).
3. You have private data in your class, which, according to the
standard, the compiler is free to move around and, much to your
chagrin, pad (sometimes that is fully or partially controllable by
compiler switches and/or #pragmas).
Anyway, the point is that you are probably prematurely optimizing (cf.
the section titled "Beware Premature Optimization" in
http://www.gotw.ca/publications/mill09.htm).
Cheers! --M