Vector of char

Feb 18, 2016 at 7:48pm
I want to get long int value from vector <char>, so I have two working versions:


First solution:
 
return *(long*)(vecSample.data()+offset);


Second solution:
 
return *reinterpret_cast<const long*>(&vecSample.at(offset));

The question is: Which version is better?

If it's better it means faster or safer? I know that vectors are contignous so I shouldn't worry for real time pointer.
Anyway, second idea looks uglier because of reinterpret_cast stuff. Are they the same?

And the way the value is read, it's better (by better I mean faster in that case) to read by data()+offset or by at(offset)?
What do you think?

Last edited on Feb 18, 2016 at 10:14pm
Feb 18, 2016 at 8:29pm
Note that the two snippets you posted are not functionally equivalent. *(long*)vecSample.data()+offset is equivalent to (*(long*)vecSample.data()) + offset.

I always go with the C-style cast, myself.
Feb 18, 2016 at 8:58pm
Both versions seem unsafe. The .at() member function does range checking, which might slow things down (but whether that matters depends on the usage).

But in either case a long will occupy more than a single character, which could lead to out-of-bounds access. If you wanted safety you might need to use sizeof(long) as well as vector size() somewhere in the code.
Feb 18, 2016 at 10:14pm
@helios
Sorry, I forgot the ( )

@Chervil
Yea, I have that solution implemented already :)

Thanks you both for the answers

Last edited on Feb 18, 2016 at 10:18pm
Feb 18, 2016 at 10:42pm
I tried various versions, this was one which seemed both safe and still reasonably fast - but speed may be compiler dependent.
 
return  ( (offset >=0) && (sizeof(long) + offset <= vecSample.size()) ) ? *reinterpret_cast<const long *>(&vecSample[offset]) : 0;


For the code I tested, &vecSample[offset] seemed at least as fast as any of the alternatives, and there was no difference in speed regardless of type of cast - though C++ style is considered safer in general, as the compiler is better able to check the code.
Topic archived. No new replies allowed.