POD (Plain Old Data) is a structure or data type in C++ that is compatible with the ordinary structuring of data as in C and is ideally suited for low-level programming.
Background:
POD emerged as a legacy from the C language to guarantee memory compatibility between C and C++. In C++98, POD objects had strict limitations to allow for easy byte-by-byte copying or direct serialization.
Issue:
Many programmers confuse POD with just simple structs and overlook the nuances of the standard, such as aggregation rules or the presence of non-standard constructors, which are critical in ABI compatibility and low-level operations (memcpy, serialization).
Solution:
In modern C++ with C++11, the concepts of trivial, trivially copyable, and standard-layout were introduced, clarifying the requirements more distinctly.
Code example:
struct PODType { int x; double y; }; static_assert(std::is_pod<PODType>::value, "Must be POD"); static_assert(std::is_trivially_copyable<PODType>::value, "Trivially copyable"); static_assert(std::is_standard_layout<PODType>::value, "Standard layout");
Key features:
Can a POD type have private members?
No, standard-layout requires either all members to be public, or uniform access (either all public or all private/protected).
Will a class be a POD type if it has an explicitly defined user constructor without a body?
No, the presence of a user-defined (even empty) constructor makes the type non-POD and non-trivial.
Can I use a POD type with a virtual destructor or virtual functions?
No, virtual methods make the type non-POD and non-standard-layout.
Negative case
A developer serializes a structure using memcpy, not noticing that it has a std::string (not POD), resulting in incorrect data upon reading.
Pros:
Cons:
Positive case
The entire structure is POD or trivial, serialization is via memcpy, no references or std containers inside.
Pros:
Cons: