1

I want to map data from an array to a C++ class. The class will ONLY have private member variables, no inheritance or virtual stuff. Is this safe or should I use a struct in C++?

void main(void)
{
    uint8_t data[50];
    MyClass *msg;

    msg = nullptr;

    for (int i = 0; i < 50; i++)
    {
        data[i] = i;
    }

    msg = (MyClass *) &data[0];

    cout << msg->name();
}

The class looks like this:

class MyClass
{
private:
    int name;

public:
    int name();        //Getter
    void setName();    //Setter
};
uniquenamehere
  • 1,869
  • 3
  • 31
  • 60
  • 2
    `msg = new MyClass();` what is the point of this line? If you want to initialise `msg` before assigning it properly just assign it to `nullptr`, as it stands you are leaking memory. – sjdowling Nov 14 '14 at 23:38
  • I'd recommend you to read on the subject of serialization, particularly from the boost library. Much safer than copying a struct/class in binary, and more flexible. – J-Mik Nov 14 '14 at 23:42

2 Answers2

0

You can do it for standard layout types but you need to consider alignment was well:

constexpr int bufmax = 50*sizeof(MyClass);
alignas(X) char buffer[bufmax];

However just because you can doesn't mean you should.

sjdowling
  • 2,994
  • 2
  • 21
  • 31
-1

It is safe to use a uint8_t[] as a storage buffer if that's what you're asking, yes. A valid use would look something like this:

constexpr size_t array_size = 5;
alignas(MyClass) uint8_t data[sizeof(MyClass) * array_size ];
MyClass *msg = new(data) MyClass[array_size];

Then you can use msg however you'd like. Your usage is incorrect - if you populate data with uint8_t values, you cannot access it as if it were a MyClass. That would result in undefined behavior.

Red Alert
  • 3,786
  • 2
  • 17
  • 24
  • The only difference I see here is that you guarantee that data[] is the same size as the class? – uniquenamehere Nov 14 '14 at 23:46
  • 1
    Close, but no cigar. You've overlooked alignment at least, and I'm pretty sure all binary format guarantees go away if the class isn't a `standard-layout` type. IE, the compiler can rearrange members at will. – Mooing Duck Nov 14 '14 at 23:47
  • @RedAlert: Uh, alignment is very relevant. `sizeof(MyClass)` guarantees you _the right number_ of bytes. It does not guarantee they are aligned in _the right place in memory_. `double` in x64 has to be aligned on a 8 byte mark, but your code doesn't guarantee that `data` starts at an 8 byte mark. – Mooing Duck Nov 14 '14 at 23:54