c ++ POD初始化

时间:2010-08-30 18:41:15

标签: c++ pod

我已经阅读了C ++中的POD对象。我想要将POD结构写入文件。所以它应该只有没有ctors / dtors等的公共数据。但据我所知它可以有静态功能。那么我可以在这里使用“命名构造函数idiom”吗?我需要动态初始化,但我不想在每次struct初始化时复制参数检查 这是一个简单的例子(它只是简单示例,而不是工作代码):

struct A
{
  int day;
  int mouth;
  int year;

   static A MakeA(const int day, const int month, const int year)
   {  
      // some simple arguments chech
      if ( !(day >= 1 && day <= 31) || !(month >=1 && month <=12) || !(year <= 2010) )
         throw std::exception();

      A result;
      result.day = day;
      result.month = month;
      result.year = year;
      return result;
   }
};

所以我有一些构造函数和POD结构,我可以简单地将其写入文件中?这是正确的吗?

3 个答案:

答案 0 :(得分:4)

那应该没事。

您甚至可以拥有非静态成员函数(只要它们不是虚拟的)

你不能拥有一个自动的东西(如ctor / dtor)。你明确打电话的事情很好。

答案 1 :(得分:1)

如果你编写流操作符,它可以简化生活 它不像写二进制文件要快得多(因为你需要编写代码来转换为不同的字节序格式),而现在的空间实际上是无关紧要的。

struct A
{
  int day;
  int mouth;
  int year;

   A(const int day, const int month, const int year)
   {  
      // some simple arguments chech
      if ( !(day >= 1 && day <= 31) || !(month >=1 && month <=12) || !(year <= 2010) )
         throw std::exception();

      this->day    = day;
      this->month  = month;
      this->year   = year;
   }
};
std::ostream& operator<<(std::ostream& str, A const& data)
{
    return str << data.day << " " << data.month << " " << data.year << " ";
}
std::istream& operator>>(std::istream& str,A& data)
{
    return str >> data.day >> data.month >> data.year;
}

通过这个定义,标准算法的整个plethera变得可用且易于使用。

int main()
{
    std::vector<A>    allDates;
    // Fill allDates with some dates.

    // copy dates from a file:
    std::ifstream  history("plop");
    std::copy(std::istream_iterator<A>(history),
              std::istream_iterator<A>(),
              std::back_inserter(allDates)
             );

    // Now  save a set of dates to a file:
    std::ofstream  history("plop2");
    std::copy(allDates.begin(),
              allDates.end(),
              std::ostream_iterator<A>(history)
             );
}

答案 2 :(得分:1)

你是对的。这只是一个普通的旧数据。没有有趣的虚拟表指针或类似的东西。

现在,我仍然不确定使用fwrite将数据写入文件是一件好事。您可以执行此操作并fread数据,前提是执行fread的程序使用的编译器版本与用于执行fwrite的编译器相同。但是,如果您切换编译器,平台,有时甚至是版本,可能会发生变化。

我建议像Protocol Buffers这样的工作来完成使数据结构持久化的工作。

相关问题