4

I have a blob of data I am parsing. It has mixed data types, some doubles followed by some floats. This is how I have gone about parsing out the doubles into a vector. I just want some feedback on if there is a better way to do this. I feel like there may be a way to do this more concisely.

BlobData::MyDoubles is a vector<double>;

    BlobData::MyDoubles MyClass::GetDataPointsFromBlob(const text* blob, const int numDoubles)
{
    BlobData::MyDoubles::value_type* doubles = new BlobData::MyDoubles::value_type[numDoubles];
    memcpy(doubles, blob, numDoubles*sizeof(BlobData::MyDoubles::value_type));
    BlobData::MyDoubles returnVal =  BlobData::MyDoubles(doubles,doubles+numDoubles);
    delete [] doubles;
    return returnVal;
}
gfree
  • 479
  • 7
  • 16

1 Answers1

3

You don't need an extra allocation as vector will copy the content no matter what. To convert data from a pointer to void/char/whatever_blob use reinterpret_cast that is exactly what it was made for. And you can construct vector with a pair with iterators (pointers are iterators).

vector<double> GetDataPoints(const char* blob, const int numDoubles) {
    const double* dbegin = reinterpret_cast<const double*>(blob);
    return { dbegin, dbegin + numDoubles };
}

Also note that in the end we don't have any sizeof(double) because of pointer arithmetic in C++

P.S. Unlike your code (which has no exception safety) this one has strong exception safety. And for the size type is better to use dedicated size_t.

Teivaz
  • 5,462
  • 4
  • 37
  • 75
  • It is not entirely obvious if OP is worried with being pedantic. The snippet you posted likely breaks strict aliasing – Passer By Nov 21 '17 at 02:19
  • Had to mix a const_cast in there as well for the blob, but everything else seems to work. – gfree Nov 21 '17 at 15:13
  • @PasserBy this might break strict aliasing. However this is common technique. And from my experience it works on many platforms as well as mobile once. – Teivaz Nov 21 '17 at 21:00
  • @gfree using const_cast is a rarely justified – Teivaz Nov 21 '17 at 21:02