| High Integrity CPP Rule 17.11 | When passing vector types to C style functions use '&v[ 0 ]'. |
| Justification |
The STL class vector is designed to be usable as a C style array. The elements in a non-empty vector are guaranteed to be stored contiguously so it is possible to use the address of the first element in the container as a pointer to an array of elements. The best way to do this is by '&v[0]' where v is a vector of some object with a C compatible type. Other methods of treating a vector as an array are implementation defined and not portable.
extern "C" void functionTakingArrayOfInt( int i[] );
extern "C" void functionTakingPointerToArrayOfInt( int* pvi );
void goodWayToUseCFunctionWithVector( vector< int >& vec )
{
assert( false == vec.empty() && "this doesnt work with empty vectors!" );
functionTakingArrayOfInt( &vec[ 0 ] ); // ok
functionTakingPointerToArrayOfInt( &vec[ 0 ] ); // ok
}
void badWayToUseCFunctionWithVector( vector< int >& vec )
{
functionTakingArrayOfInt( vec.begin() ); // may not work as intended!
}
|
| Reference |
Effective STL Item 16; |