using a char array to hold an array of arbitrarily sized objects, alignment issues?
I want to pass in an array of parameters to SQLBindParameters, and have this array held in a 开发者_开发知识库char array(since I don't know the type beforehand) (I want all the elements in the 'array' to be the same).
I'll have a pointer to a sample parameter type, and the size of the parameter.
void *buffer = getBuffer();
int bufferLength = getBufferLength();
const int numElements = 200; //for example
char *array = new char[bufferLength * numElements];
for(int i=0; i < numElements; ++i)
{
memcpy(array + (i * bufferLength), buffer, bufferLength)
}
// now use array in SQLBindParameter call
will this work as expected, without any alignment issues? (i.e., the same as if I had just declared an array of the right type to start with)
Assuming that you're using vector
with an allocator that uses operator new
under the hood, then the C++ standard guarantees that an array of char
allocated with new
will be aligned suitably for use with any data type.
EDIT: Yes, new char[]
is guaranteed to be aligned for use with any type.
EDIT2: Do note that a local (stack) array char foo[]
has no such alignment guarantees.
A vector
is just a wrapper around a contiguous block of dynamically allocated memory, in other words, an array. So, if this program would work with an array allocated with malloc
or new
, it should continue to work with a vector
.
(Unless it only worked "accidentally" with an array, of course, but the vector
is unlikely to introduce extra problems.)
The C++ standard in 23.2.4 guarantees that each element of a vector<> is stored contiguously:
The elements of a vector are stored contiguously, meaning that if v is a vector where T is some type other than bool, then it obeys the identity &v[n] == &v[0] + n for all 0 <= n < v.size().
It's important to notice what it says about vector < bool > , vector < bool > is a specialized vector<> that happens to try to "optimize space allocation", in some implementations it does so by storing each boolean value in a bit which pretty much renders pointer arithmetic useless.
精彩评论