I want to use std::vector for dynamically allocating memory. The scenario is:
int neededLength = computeLength(); // some logic here
// this will allocate t
The reason it looks ugly is because you're at the borderline of nice and clean C++ style code and nice and clean C style code. The C++ code uses iterators, the C code uses pointers and sizes.
You could create some glue to circumvent these problems:
template< typename at_Container, typename at_Function >
void for_container( at_Container& c, at_Function f ) {
f( &c[0], c.size() );
}
and call it in the client code.
void afunction( int* p, size_t n ) {
for( int* p = ap; p != ap+n; ++p ) {
printf( "%d ", *p );
}
}
void clientcode() {
std::vector<int> ints(30,3);
for_container( ints, afunction );
}
If you're using std::vector
just for its RAII properties (so that it will free the memory for you), and you don't actually need it to resize or anything, you might be better off using a Boost scoped_array
boost::scoped_array<TCHAR> buffer( new TCHAR[neededLength] );
callFunction( buffer.get(), neededLength );
scoped_array
will call delete[]
on the array when it goes out of scope.
No.
It's really odd that nobody know this!!! in C++11 you could use:
buffer.data()
it could get the address of the vector I have test it:
vector<char>buffer;
buffer.push_back('w');
buffer.push_back('h');
buffer.push_back('a');
buffer.push_back('t');
buffer.push_back('\0');
char buf2[10];
memcpy(buf2,buffer.data(),10);
Specification here.
Try &(buffer.front())
, but it's not much prettier :)