Re: Problem with using char* to return string by reference
On Wed, 11 Jun 2008 00:09:34 +0200, Norbert Unterberg
<nunterberg@newsgroups.nospam> wrote:
While we are at it, what is the best method to fill a std::string with what
functiosn like RegQueryValueEx()? MFC's CString class has
GetBuffer/ReleaseBuffer to fill the string buffer without doing an extra copy or
allocating extra memory, but what do you experts do with a std::string?
The "official" answer is to use a std::vector and copy it to a std::string.
In practice, you can probably get away with something like:
std::string s;
// n and x conform to usual Windows API definition.
int n = maximum length including nul terminator;
s.resize(n);
int x = SomeAPI(&s[0], n);
// Assume x < n and no error...
s.resize(x);
At least I don't know of any implementation for which this would fail, but
people will object that std::string may not use contiguous storage. This is
true, but again, I don't know of any implementation that has taken
advantage of this misguided freedom. Unfortunately, the first resize will
zero-fill the string; among other things, the basic_string-alike class I
wrote years ago provides a function "uninitialized_resize" to get around
this minor inefficiency.
--
Doug Harrison
Visual C++ MVP