
On 8/11/2013 8:53 PM, Marshall Clow wrote:
On Aug 11, 2013, at 5:45 PM, Edward Diener
wrote: On 8/11/2013 3:39 PM, Rob Stewart wrote:
On Aug 11, 2013, at 9:50 AM, Edward Diener
wrote: On 8/10/2013 8:59 PM, Rob Stewart wrote:
On Aug 10, 2013, at 8:25 AM, Edward Diener
wrote: std::vector<TYPE> is the C++ way of specifying arrays.
If you do that, don't use resize() and size(). Use reserve() and capacity(), and don't forget to push_back() one element to make &v[0] valid.
I do not follow this. Especially the bit about pushing back an element. Vectors can be empty as I am sure you know and there are still valid.
Accessing an element of an empty vector is undefined behavior. Calling resize() to reserve space also causes elements to be initialized, which is often not needed when calling an API that indicates the number of bytes written.
What I often do is the following:
std::vector<char> v; v.reserve(1024); v.push_back(0); read(&v[0], v.capacity());
I don't know what "read(&v[0], v.capacity())" is doing here. is this supposed to be a named pipe 'read'-like function ? Whatever it is either the 'read' will:
1) read a byte at a time and add it to the end of the vector via a push_back
I can't see it doing that - because it would need a reference to the vector to do the push_back.
In my prefereed interface it is passing a reference to a vector which is being filled in with the data read. Gee, that's too simple. Must be something seriously wrong with it. I acknowledge it might also be advantage to pass some limit as a second parameter, so only that number of elements gets filled in at the max. But in either case it does not make sense to me to prime the data with some mythical first element, or worry about what has been reserved. I don't design with C-style pointers, to some possible array of some possible size, of elements. I thought everyone had given up on that sort of unnecessary complication a long time ago when std::vector became the defacto standard in C++ for dynamic arrays. I am not against fixed size arrays if that is what some interface calls for, but if we are talking about dynamic arrays of elements then std::vector seems to me to be the way to do it.