Question

Are the class members of this simple class continous in memory?

class A{
    A(){ /* somecode */}
    ~A();
    Eigen::Matrix<5,1,double> a;
    Eigen::Matrix<9,1,double> b;
};

std::vector<A> vec(10);

char * p = interprete_cast<char*>(&vec[0]);

// the pointer p can now continously access all "a" and "b" in continous order ->  (a,b,...,a,b)

// For example write all data to a binary file!
file.write( p, sizeof(A)*vec.size() )

In other posts there was something mentioned about #pragma pack and so on? Is this needed here? Link

or is it better to pack the members into a struct

Thanks alot :-)

Was it helpful?

Solution

This is a bad, bad way to serialize things. Most probably, Eigen::Matrix objects involve heap allocation (i.e. they have pointers) which means you'll be unpleasantly surprised when you deserialize them.

In addition to that, you would have to guarantee that alignment hasn't changed between two programs (it's very easy to change it by turning on some optimization options, let alone by porting to another architecture).

A proper way to serialize would be to either write your own serializing code that writes things in a portable manner or (better yet) find a ready-to-use one (depending on your library).

Going back you your question - no, it is not guaranteed that instances of A are contiguous. In fact, they are most probably aligned to the "natural" word size (they would be contiguous if sizeof(A) is divisible by that word size).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top