Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: POD Pros\Cons

Tags:

c++

  • 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?
like image 568
Jonathan Livni Avatar asked Dec 24 '10 07:12

Jonathan Livni


2 Answers

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.

like image 173
mmmmmmmm Avatar answered Sep 17 '22 18:09

mmmmmmmm


If you have a gazillion small objects, ensuring that those objects are POD can be a huge advantage.

  1. You can calloc() or malloc() a large chunk of them, saving you a gazillion calls to constructors.
  2. 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.

like image 29
kfmfe04 Avatar answered Sep 19 '22 18:09

kfmfe04