簡體   English   中英

C++ POD初始化

[英]c++ POD initialization

我已經閱讀了 C++ 中的 POD 對象。 我想將 POD 結構寫入文件。 所以它應該只有公共數據,沒有 ctors/dtors 等。但據我所知,它可以有靜態功能。 那么我可以在這里使用“命名構造函數成語”嗎? 我需要動態初始化,但我不想在每個結構體初始化時重復檢查參數這里是一個簡單的例子(它只是簡單的例子,不是工作代碼):

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 結構,我可以簡單地將其寫入文件? 它正確嗎?

那應該沒問題。

你甚至可以有一個非靜態成員函數(只要它們不是虛擬的)

你不能有自動調用的東西(比如ctor/dtor)。 你明確調用的東西很好。

如果你編寫流操作符,它會讓生活變得更簡單。
並不是說用二進制編寫會明顯更快(因為您需要編寫代碼以轉換為不同的字節序格式),而且現在空間幾乎無關緊要。

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;
}

有了這個定義,大量的標准算法變得可用且易於使用。

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)
             );
}

你是對的。 那只是一個普通的舊數據。 沒有有趣的虛擬表指針或類似的東西。

現在,我仍然不確定簡單地使用fwrite將數據寫入文件是否是個好主意。 你可以做到這一點, fread的條件是該做的程序把數據傳回fread與相同版本用來做編譯器的書面fwrite擺在首位。 但是,如果您切換編譯器、平台,有時甚至版本,情況可能會發生變化。

我建議使用Protocol Buffers 之類的東西來完成使數據結構持久化的工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM