- What are the pros and cons of using Plain Old Data (POD) structs\classes in C++?
- In what cases should one prefer using them over non-PODs?
- Specifically, do PODs have advantages while working with serialization frameworks? Perhaps when working cross-platform and cross-language?

- 121,568
- 97
- 310
- 388

- 101,334
- 104
- 266
- 359
4 Answers
If you have a gazillion small objects, ensuring that those objects are POD can be a huge advantage.
- You can calloc() or malloc() a large chunk of them, saving you a gazillion calls to constructors.
- For persistence, rather than streaming out the objects one at a time, you can use fwrite() and fread() entire chunk of them for speed.
The disadvantage is, you have to keep your mind flexible to handle non-OOP PODs in your code. PODs are a fallback from old-style C code where you know and care about the layout of your data. When that layout is well-defined, you may optimize by working chunks of memory rather than lots of little pieces.
Please note that what I describe above applies to trivially laid out structures. In other words, if you call type_trait's std::is_trivially_copyable() on this type, you will get true. The requirements for POD are actually even stronger than that of trivially-copiable structures. So what I just described above applies to all PODs and even some non-PODs which happen to be trivially-copiable.

- 14,936
- 14
- 74
- 140
There is one advantage of POD in conjunction with constants.
If you declare/define a constant and you use a POD type for it the whole POD is put into the (constant) data section of the executable/library and is available after loading.
If you use a non-POD the constructor must run to initialize it. Since the order of running constructors of static classes in C++ is undefined you cannot access static A from static B's constructor or any code that is invoked from within static B's constructor.
So using PODs in this case is safe.

- 15,269
- 2
- 30
- 55
-
1"the order of running constructors of static objects in C++ is undefined" - if they're in different translation units. – Steve Jessop Dec 24 '10 at 10:13
PODs can be used in C interfaces which means that you can have a library written in C++ but with a C interface which can advantageous.
The disadvantage is that you can't use a constructor to put burden of initialization onto the type itself - the user code will have to take care of that.

- 167,383
- 100
- 513
- 979
pods have some subtle advantage. I don't know any portable way to calculate memory size required for new[] operator if array elements are non-pod, so it is dificult to use safely placement new[] operator for such an array. If nonpod structure has a destructor, new[] needs extra space to store array size, but this extra size is implementation-dependent (althogh usually it is sizeof(size_t) + (perhaps) some padding to provide proper alignment)

- 3,106
- 1
- 21
- 31