Topic: string class: char* buffer()


Author: d96-mst@nada.kth.se (Mikael Steldal)
Date: 1996/11/22
Raw View
I think it will be useful to have three member function like this in
the string class:

charT* buffer() const;
void setsize(size_type n);
void setsize(void);

buffer() should return a non-const pointer to a buffer with the length
capacity() which is valid until you call any non-const member functions
of the string.

setsize(size_type) would work like resize(size_type) except that it
won't pad (and then it doesn't need the second parameter).

setsize(void) would work like s.setsize(strlen(s.buffer())) and use
traits::eos(). It should set size equal to capacity() if no terminator
is found.

That would be useful and efficient if you need to do something like
this:

{
 string s, t;
 FILE* TheFile;
 size_t BytesRead;

 s.reserve(TheNumberOfBytesIWantToRead);
 BytesRead = fread(s.buffer(),1,
                   min(s.capacity(),TheNumberOfBytesIWantToRead,
                   TheFile);
 s.setsize(BytesRead);

 fgets(t.buffer(),t.capacity(),TheFile);
 s.setsize();
}

fread() and fgets() is of course a bad examples since you can use
I/O-streams instead, but it can be useful if you are working with a C
library or an API which has no C++ wrapper. I can't find out any other
way of doing this without unnessesary data copy.

If data() is changed as I'll propose in the other article, maybe
buffer() should be specified to return the same pointer as data(), only
the constness will differ.
---
[ comp.std.c++ is moderated.  To submit articles: try just posting with      ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu         ]
[ FAQ:      http://reality.sgi.com/employees/austern_mti/std-c++/faq.html    ]
[ Policy:   http://reality.sgi.com/employees/austern_mti/std-c++/policy.html ]
[ Comments? mailto:std-c++-request@ncar.ucar.edu                             ]