On 10/26/2017 01:17 PM, Pedro Alves wrote:
On 10/26/2017 07:54 PM, Martin Sebor wrote:

(...) in the general case, it is preferable to
declare each variable at the point where its initial value is known
(or can be computed) and initialize it on its declaration.

With that I fully agree, except it's not always possible or
natural.  The issue at hand usually turns up with
conditional initialization, like:

void foo ()
{
  int t;
  if (something)
    t = 1;
  else if (something_else)
    t = 2;
  if (t == 1)
    bar ();
}

That's a simple example of course, but more complicated
conditionals aren't so easy to grok and spot the bug.

In the case above, I'd much prefer if the compiler tells me
I missed initializing 't' than initializing it to 0 "just
in case".

Sure.  A similar observation could be made about std::string
or std::vector vs a plain C-style array, or for that matter,
about almost any other class.  But it would be absurd to use
such examples as arguments that it's better to define classes
with a no-op default constructor.   It's safer to initialize
objects to some value (whatever that might be) than not to
initialize them at all.  That's true for fundamental types
and even more so for user-defined classes with constructors.

IMO, a good rule of thumb to follow in class design is to have
every class with any user-defined ctor either define a default
ctor that puts the object into a determinate state, or make
the default ctor inaccessible (or deleted in new C++ versions).
If there is a use case for leaving newly constructed objects
of a class in an uninitialized state that's an exception to
the rule that can be accommodated by providing a special API
(or in C++ 11, a defaulted ctor).

Martin

Reply via email to