Initializing an object to all zeroes

后端 未结 12 609
离开以前
离开以前 2020-12-03 01:27

Oftentimes data structures\' valid initialization is to set all members to zero. Even when programming in C++, one may need to interface with an external API for which this

12条回答
  •  一向
    一向 (楼主)
    2020-12-03 02:07

    The best method for clearing structures is to set each field individually:

    struct MyStruct
    {
      std::string name;
      int age;
      double checking_account_balance;
      void clear(void)
      {
         name.erase();
         age = 0;
         checking_account_balance = 0.0;
      }
    };
    

    In the above example, a clear method is defined to set all the members to a known state or value. The memset and std::fill methods may not work due to std::string and double types. A more robust program clears each field individually.

    I prefer having a more robust program than spending less time typing.

提交回复
热议问题