Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ and packed struct

Tags:

c++

class

struct

I have database project that I want to move from C to C++. In this C project I have lots of small packed structs, that I write directly to file or read from mmaped file - e.g. directly from memory address.

I need the class in-memory representation, to be exactlybthe same as if I use plain old C struct. I believe this is called POD or C++ standard layout.

I can proceed in several ways:

I can do class, bu I worry that if I add methods to this struct, probably the internal structure will be changed.

If I wrap the a structure into class, I will need to create / destroy classes all the time, along with the structs.

If I do it C - OO style, I will need to supply pointer to every function, e.g.

static const char *Pair::getKey(const void *mem);

I can also make the struct a field and do something similar

void Pair::setMem(const void *mem);
const char *Pair::getKey();

but the more I see this, the less I like it, because there is no real advantage.

Anything I am missing?

like image 205
Nick Avatar asked Sep 07 '26 04:09

Nick


1 Answers

If I add methods to this struct, probably the internal structure will be changed.

That's wrong; to satisfy your needs what you want is to keep your structure a POD, for which essentially you don't want:

  • non-trivial constructors/destructors/assignment operators;
  • virtual functions or virtual base classes;
  • different access specifiers for data members.

(there are some additional restrictions (see C++11 §9 ¶6-10), but they are not particularly relevant in your case)

The "POD" thing implies two things:

  • that your class is "standard layout", which roughly means "laid out in a well-defined manner, the same way as C would do" (which assesses your primary concern);

    adding methods shouldn't break stuff, since, as they aren't be virtual, they are translated as free functions which take a pointer to the object as hidden parameter, and that requires no modification to the original C layout. static methods are just free functions with different scoping, so in general they are a non-issue.

  • that your class can be freely copyable with a memcpy without stuff breaking, which is probably what you want if you read it straight from file (either with mmap or with fread);

    this is accounted for by the "triviality" of the constructors (i.e. if they are skipped nothing bad happens to your objects) and by the absence of virtual members, which means that you don't risk overwriting the vptr with a stale one read from the file.

like image 102
Matteo Italia Avatar answered Sep 09 '26 18:09

Matteo Italia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!