Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
249 views
in Technique[技术] by (71.8m points)

c++ - Constructor to specify zero-initialization of all builtin members?

Is there a simpler way for a class's constructor to specify that all members of built-in type should be zero-initialized?

This code snippet came up in another post:

struct Money
{
    double amountP, amountG, totalChange;
    int twenty, ten, five, one, change;
    int quarter, dime, nickel, penny;

    void foo();
    Money()  {}
};

and it turned out that the problem was that the object was instantiated via Money mc; and the variables were uninitialized.

The recommended solution was to add the following constructor:

Money::Money()
  : amountP(), amountG(), totalChange(),
    twenty(), ten(), five(), one(), change()
    quarter(), dime(), nickel(), penny()
{
}

However, this is ugly and not maintenance-friendly. It would be easy to add another member variable and forget to add it to the long list in the constructor, perhaps causing a hard-to-find bug months down the track when the uninitialized variable suddenly stops getting 0 by chance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For something working in C++98, you can use Boost's value_initialized: (live example)

#include <boost/utility/value_init.hpp>
...
struct Money
{
    boost::value_initialized<double> amountP, amountG, totalChange;
    boost::value_initialized<int> twenty, ten, five, one, change;
    boost::value_initialized<int> quarter, dime, nickel, penny;

    void foo();
    Money()  {/*every member is 0*/}
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...