Re: Problem with using char* to return string by reference
* Doug Harrison [MVP]:
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.
It's safe, and contigous storage for string will be guaranteed in C++0x (voted
into WP a few years ago, at Lillehammer -- I recall the location because I'm
Norwegian!, and forget the exact year because time just slips by... :-) ).
As of late last year (draft N2461) the wording was, in ?21.3.1/3,
"The char-like objects in a basic_string object shall be stored contiguously.
That is, for any basic_string object s, the identity &*(s.begin() + n) ==
&*s.begin() + n shall hold for all values of n such that 0 <= n < s.size()."
Cheers, & hth.,
- Alf
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?