c++ POD initialization
I've read about POD objects in C++. I wanna have a POD struct to be written into a file. So it should have only public data with no ctors/dtors etc. But as 开发者_如何学Cfar as i know it can have static function in it. So can I use "named constructor idiom" here? I need dynamic initialization, but I don't want to duplicate arguments checking at every struct initialization Here is a simple example (it's just simple example, not a working code):
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;
}
};
So I have some kind of a constructor and a POD structure that I can simply fwrite to a file? It it correct?
That should be fine.
You can even have a non-static member functions (as long as they are not virtual)
You cannot have something that is called automatically (like ctor/dtor). Thingsthat you explicitly call are fine.
If you write the stream operators it makes life a lot simpler.
Its not as if writing in binary is significantly faster (as you need to write the code to convert for different endian formats) and space nowadays is practically irrelevant.
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;
}
With this defined the whole plethera of standard algorithms becomes available and easy to use.
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)
);
}
You are correct. That's just an ordinary old piece of data. No funny virtual table pointers or anything like that in it.
Now, I'm still not sure it's all that good an idea to simply use fwrite
to write the data to a file. You can do that and fread
the data back in provided that the program that does the fread
is written with the same version of the compiler used to do the fwrite
in the first place. But if you switch compilers, platforms, or sometimes even versions, that may change.
I would suggest something like Protocol Buffers to do the work of making your data structure persistent.
精彩评论