Share via


CString

A CString object consists of a variable-length sequence of characters. CString provides methods and operators using a syntax similar to that of Basic. Concatenation and comparison operators, together with simplified memory management, make CString objects easier to use than ordinary character arrays.

CString does not have a base class.

CString objects also have the following characteristics:

  • CString objects can grow as a result of concatenation operations.
  • CString objects follow, value semantics. Think of a CString object as an actual string, not as a pointer to a string.
  • You can freely substitute CString objects for const char* and LPCTSTR function arguments.
  • A conversion operator gives direct access to the characters of the string as a read-only array of characters (a C-style string).

Tip   Where possible, allocate CString objects on the stack rather than on the heap. This saves memory and simplifies parameter passing.

CString assists you in conserving memory space by allowing two strings sharing the same value also to share the same buffer space. However, if you attempt to change the contents of the buffer directly (not using MFC), you can alter both strings unintentionally. CString provides two methods, CString::LockBuffer and CString::UnlockBuffer, to help you protect your data. When you call LockBuffer, you create a copy of a string, then set the reference count to –1, which locks the buffer. While the buffer is locked, no other string can reference the data in that string, and the locked string will not reference another string. By locking the string in the buffer, you ensure that the exclusive hold of the string on the data remains intact. When you have finished with the data, call UnlockBuffer to reset the reference count to 1.

Remarks

Windows CE does not support the following methods of the CString class:

  • AnsiToOem
  • Collate
  • FormatMessage
  • OemToAnsi

Requirements

  Windows CE versions: 1.0 and later
  Header file: Declared in Afx.h
  Platform: H/PC Pro, Palm-size PC, Pocket PC

See Also

Simple Value Types