It is sometimes useful to use the starting address std::vector and temporarily treat this address as the address of a regularly allocated buffer.
For example, replace this:
char* buf = new char[size]; fillTheBuffer(buf, size); useTheBuffer(buf, size); delete[] buf;
With the help of this:
vector<char> buf(size); fillTheBuffer(&buf[0], size); useTheBuffer(&buf[0], size);
The advantage of this, of course, is that the buffer is freed automatically, and I don't need to worry about delete[] .
The problem with this is related to size == 0. In this case, the first version works fine. An empty buffer is "allocated", and subsequent functions do nothing by size, they get size == 0.
The second version, however, does not work if size == 0, since a call to buf[0] can rightfully contain the statement that 0 < size .
So, is there an alternative to idiom &buf[0] that returns the address of the start of the vector, even if the vector is empty?
I also considered using buf.begin() , but according to the standard it is not even guaranteed to return a pointer.
c ++ pointers vector
shoosh
source share