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;
}
1
  • Are you concerned with being pedantic and not breaking strict aliasing and pointer arithmetic rules? Commented Nov 21, 2017 at 2:18

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

It is not entirely obvious if OP is worried with being pedantic. The snippet you posted likely breaks strict aliasing
Had to mix a const_cast in there as well for the blob, but everything else seems to work.
@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.
@gfree using const_cast is a rarely justified

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.