Re: CString help
On Sat, 23 Jun 2007 18:50:59 -0400, Joseph M. Newcomer
<newcomer@flounder.com> wrote:
Of course, if you use GetWindowTextLength() first and allocate a buffer of the right size,
you have a reasonble confidence that you will get all the characters (the liklihood that
someone else will change the string contents from another thread is vanishingly small, and
is a case that could be ignored, in that if you GetTextLength() == N and you allocate a
buffer of N+1 characters, and get N characters back, then either it is dead-on-accurate or
somebody wrote a longer string it between the two calls, and a programmer may choose to
ignore that situation.
joe
Sure, that's how I actually did it in my string class:
const size_type len = ::GetWindowTextLength(hWnd);
uninitialized_resize(len);
// Windows doesn't truncate in the strncpy sense; it always
// nul-terminates.
resize(::GetWindowText(hWnd, raw_data(), len+1));
return *this;
I wrote this almost 10 years ago as part of a std::basic_string-like class
that provides true COW, which I still use today. I talked some more about
it here:
http://groups.google.com/group/microsoft.public.vc.stl/msg/fa3c6c5d1ba99453
My string class always makes room for the terminating nul, so the
uninitialized_resize call is indeed correct. That function differs from
resize in that it doesn't initialize the new space when growing the string,
and it was written for exactly this usage pattern. The function raw_data()
is like data() except it returns a non-const pointer. Ironically, I can't
use the &s[0] approach, because s[0] returns a reference object that is
actually of class type, and taking its address returns an iterator, not a
pointer. This is where I deviated from the standard, and it was necessary
to support real COW.
--
Doug Harrison
Visual C++ MVP