A Comfortable Couch

Monday, February 21, 2005

C++ Question

Is this valid in the C++ STL?
std::vector<unsigned char> buffer;

memcpy(&buffer.front(), "foo", strlen("foo"));
When I say legal, I don't mean will it compile, it does without warning. I mean, does STL guarantee that when I do &buffer.front() that the returned pointer points to the raw internal array. It does indeed work that way in MSVC++ 7.1, but is that portable?


Johan Petersson said...

The canonical way of getting the pointer to contiguous storage in a vector is &buffer[0]. That is indeed guaranteed to work portably.

&buffer.front() will give the same result as &buffer[0] in your example, so that's safe too. I'm not sure if front() is well-behaved if the vector can be empty, though. Probably not.

4:59 AMlink  
Anonymous said...

char[8] ch = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 }

long some_long=0;

How can I concatenate ch into some_long?

So that some_long=12345678;

9:12 PMlink  

Post a Comment

<< Home