Re: simple question about BSTR and CString
On Wed, 26 Nov 2008 13:50:01 -0000, Daniel James
<wastebasket@nospam.aaisp.org> wrote:
That used to happen when you assigned one CString object to another in
VC6;
Still does.
the two CStrings could share memory until one of them was altered.
This is a space-optimization known as "Copy On Write" or COW.
COW never happened when assigning a BSTR or simple C character array to
a CString; it could only happen with two (or more) CStrings as each
object sharing the data needs to be able to make a copy internally if
its value changes.
The trouble with COW is that it's very difficult to make it efficient,
especially if strings are used in more than one thread. For this reason
the libraries shipped with current Visual C++ products no longer use
COW, so each CString always has its own copy of the data.
No, CString remains COW.
The current runtimes do, however, use an optimization called the "small
string optimization" (in which heap allocation is not required for
strings below a certain size). This turns out to be a more effective
optimization in most cases, especially in multi-threaded applications.
You've described std::string circa VC.NET 2002 and on, not MFC's CString,
which continues to use COW. However, the std::string class was never really
COW, as the standard effectively forbade it by requiring string::reference
to be a real reference. The reference-counting it did permit was largely
ineffective, imposed various strange rules on the user, and was the source
of some very subtle usage traps. I always called it "copy-just-in-case",
because it required unsharing and marking as unshareable whenever the user
obtained a non-const iterator, pointer or reference into the string, which
might later be used to write to the string. This included much read-only
usage of iterators and operator[]. It was only after doing something
defined to invalidate iterators, references, and pointers that the
std::string would be marked shareable again. The major flaw in this
approach was that it was not possible to make it thread-safe for read-only
access in a reasonable sort of way.
--
Doug Harrison
Visual C++ MVP