Re: replicating default constructor's "non-initializing state"
You can write a do-nothing constructor, but even that will be heavier
than not having a constructor at all:
struct C
{
C() { }
...
This is what I am doing. (I either have to do this, or make my color
struct an aggregate again by removing all my convenient non-default
constructors that I made.)
Why is this heavier? In the final compilation, shouldn't this produce
zero CPU instructions?
This is the most lightweight solution you can do in C++ if you already
have another constructor. Of course the compiler might add some implicit
function calls to it. However, if your structure only contains POD
types, they will remain uninitialized. There's a good chance the
compiler can inline this for you, and remove the empty body.
All defined functions inside of a class body are inlined by default,
even without the "inline" specifier. (The C++ standard states so,
AFAIK, it's not just a MSVC++ addition.)
Another solution to consider: simply don't write your own constructor at
all. Create a static function, or a non-member function to initialize
your data. Example:
struct Color
{
int r, g, b;
static Color Create(int ar, int ag, int ab)
{
Color c;
c.r = ar;
c.g = ag;
c.b = ab;
return c;
}
};
This has to perform two assignment operations for each member, though.
Nice tip. Another downfall is that it wouldn't be able to be used in
initializing an array of Color, since you'd have to manually call this
for each element, rather than calling the constructor right in the
array declaration.
If performance is really so important for you, you might want to use a
less convenient method:
inline void InitColor(Color& c, int ar, int ag, int ab)
{
c.r = ar;
c.g = ag;
c.b = ab;
}
The compiler will likely inline this for you in release builds. And
there's always a possibility of using a macro (ouch!).
Ha ha :) Performance isn't that important. I just want robust code,
and want my compiler's warnings to be intact.
Otherwise my tip would be to avoid early optimizations, and optimize
only after doing some benchmarking. Did you know that calling malloc
just once can be a thousand times slower than initializing those
integers with 0? There is a possibility that you're trying to optimize
something that's not likely to be anywhere near the bottleneck.
I agree 100%. Again, I am not concerned with optimization at this
time. I am concerned only with robust code. (I wish I had never
mentioned making my own constructor initialize the fields to 0 would
have the downfall of being slow.) My concern is simply that I want
the compiler's warnings for when I use "Color" before initializing
it. With its default constructor, I get those warnings. With my
default constructor, I don't (since it assumes I'm actually
initializing it, of course.)
Thanks for your time, Tom
Jason