NoSenseEtAl
NoSenseEtAl

Reputation: 30108

Most elegant way to copy POD struct/vector of structs to vector<unsigned char>

normally I am using something like

copy((uint8_t*)&POD, (uint8_t*)(&POD + 1 ), back_inserter(rawData));

copy((uint8_t*)&PODVec[0], (uint8_t*)(&PODVec[0] + PODVec.size()), back_inserter(rawData));

but I am not huge fan of this solution. Any nicer way to do this?

Upvotes: 3

Views: 2094

Answers (3)

jrok
jrok

Reputation: 55425

You could write a pair of helper functions to hide the ugly casts and pointer arithmetics:

template<typename T>
char* object_begin(T& obj)
{
    return
        &const_cast<char&>(
            reinterpret_cast<const volatile char&>(obj)
        );
}

template<typename T>
char* object_end(T& obj)
{
    return object_begin(obj) + sizeof(obj);
}

You'd use them like this:

vector<POD> vpod;
vector<unsigned char> vbytes;

copy(object_begin(vpod.front()),
     object_end(vpod.back()),
     back_inserter(vbytes));

Upvotes: 2

Wojtek
Wojtek

Reputation: 239

Step 1. Resize vector to proper size

Step 2. Use memcpy as you are dealing with raw data

#include <vector>
#include <string.h>

int main() {

    struct Foo {
        int a;
        double z;
    };

    Foo data[12];
    std::vector<char> rawdata;

    rawdata.resize(sizeof(data));
    memcpy(data, &rawdata[0], sizeof(data));

    return 0;
}

Upvotes: 0

Yochai Timmer
Yochai Timmer

Reputation: 49261

First of all, after many tests, memcpy is probably the fastest of the copy functions.

Second, you could us this for a single item:

rawData = *reinterpret_cast<POD*>(&PODVec[0]);

It will reinterpret the byte array address as an object of POD and assign to it using the assignment operator of the class.

This is possible because of section 3.9 of the standard stating:

For any object (other than a base-class subobject) of trivially copyable type T, whether or not the object holds a valid value of type T, the underlying bytes making up the object can be copied into an array of char or unsigned char. If the content of the array of char or unsigned char is copied back into the object, the object shall subsequently hold its original value.

Upvotes: 1

Related Questions