Click here to Skip to main content
15,899,679 members
Articles / Programming Languages / C++

CString-clone Using Standard C++

Rate me:
Please Sign up or sign in to vote.
4.93/5 (128 votes)
7 Dec 2011CPOL4 min read 4M   14.1K   227   568
A Drop-In replacement for CString that builds on the Standard C++ Library's basic_string template

Introduction

As much as I use and appreciate the Standard C++ Library, I've never liked its string template - basic_string<>. At times, it seems the designers went out of their way to make it difficult to use.

On the other hand, I've always loved the ease of use of MFC's CString class. It checks for NULL pointers, implicitly converts to const TCHAR*, and has some very handy member functions (Format, Load, etc.) that make string programming a breeze. But of course, I don't want to use MFC anymore. In fact, I don't want to rely on any proprietary library because I want portability.

Therefore I decided to combine the best of both worlds and create:

CStdString

This is a class (a template instantiation actually) that derives from from basic_string<TCHAR>. To the basic_string it adds the entire CString API. You get CString ease of use with 100% basic_string compatibility. In short, a CStdString object is a basic_string that (with very few exceptions (noted below) it is also a drop-in replacement for CString. The best part of this is that both APIs (basic_string and CString) are well known and well documented.

I originally submitted this article to another code site (which shall remain nameless :)) a few years ago. I like CodeProject so much I thought I'd submit it here too. I have used this class in almost every professional project I've done over the past 4 years. It has proven to be the single most useful piece of code I've ever written. It is also extensively debugged. I hope you like it. If you ever have any problems with it, please e-mail me. I'm happy to help.

I provided a simple source application here to prove some of the CString functions work but it's really just a token. The list of sample projects out there that use CString and/or basic_string is massive.

Features

  • Drop in Replacement for CString (see below for exceptions)
  • Two instantiations available at all times -- wchar_t-based version CStdStringW and char-based version CStdStringA. The name CStdString is just a typedef of one of these two.
  • Safely checks for NULL string pointer inputs (like CString) in all functions
  • Extra constructors and assignment operators to automatically convert between wide (wchar_t-based) and thin (char-based) strings for you.
  • Implicit conversion to c_str(). The C++ committee doesn't like this but I sure do.
  • Builds on several platforms, including Windows, Unix and Linux. Works with several implementations of the Standard C++ Library, including Dinkumware, GNU, CodeWarrior, and STLPort.
  • Win32 builds give you some extra goodies like UNICODE/MBCS conversion macros (just like MFCs) as well as member functions for persisting CStdString objects to and from DCOM IStreams.
  • Makes no use of any implementation details of the base class template (basic_string)
  • The derived template adds no member data to basic_string and adds no virtual functions

There are a couple of issues about this code of that I should point out.

CString Compatibility

I was unable to exactly reproduce the CString API. There are a two functions that both CString and basic_string; share, but implement differently. In these cases, I felt it best to make CStdString behave like basic_string (the base class) rather than CString. To be specific.

  • CStdString::operator[] returns characters by value (unlike CString which returns them by reference)
  • The constructor that takes a character and a count takes them in the order (count, value) which is the opposite of the order CString declares them. That's the order that basic_string<>; needs and it was impossible to implement both versions.

There were also two CString functions I could not implement at all -- LockBuffer and UnlockBuffer.

Deriving From basic_string<>

The template I wrote derives from basic_string, a class template without a virtual destructor. Any introductory text to C++ will tell you that it is dangerous to derive from a class without a virtual destructor. It can lead to behavior that is undefined. So if you were to code the following (deleting a CStdStringA through a pointer to the base class), you would technically get undefined behavior:

C++
// assign DERIVED object to  BASE pointer
std::string* pstr = new CStdStringA("Hi"); 

// delete  DERIVED through BASE class pointer -- UNDEFINED
delete pstr;   

Personally, I don't think this is much of an issue. I mean really how often do you actually do this with string objects? I have rarely (if ever) needed to dynamically allocate a string object on the heap. And if I ever do, I won't using a base-class pointer. So if you don't do this, you'll never have to worry. In fact, even if you do code this way, I doubt you'll have any problems with CStdString. I can tell you that at least with Microsoft Visual C++, even the above code runs just fine with no errors or memory leaks. I doubt many other compilers would give you problems either. However my doubt does not impose reality on the C++ world. Caveat Emptor.

History

  • 7 Dec 2011: Updated source code.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
United States United States
I've been a software developer since 1990.

While my main page is out of date (and I have therefore blanked it), you can read about the CStdString pages here

http://home.earthlink.net/~jmoleary/stdstring.htm

Comments and Discussions

 
GeneralRe: Depends on your settings Pin
Deciheximal21-Jun-03 11:26
Deciheximal21-Jun-03 11:26 
GeneralThe lowdown on CRT dlls Pin
Joe O'Leary21-Jun-03 11:39
Joe O'Leary21-Jun-03 11:39 
GeneralUsing with printf Pin
Deciheximal20-Jun-03 18:13
Deciheximal20-Jun-03 18:13 
GeneralRe: Using with printf Pin
Joe O'Leary21-Jun-03 0:07
Joe O'Leary21-Jun-03 0:07 
GeneralRe: Using with printf Pin
TomM25-Jun-03 11:28
TomM25-Jun-03 11:28 
GeneralThe portable way Pin
Joe O'Leary25-Jun-03 16:41
Joe O'Leary25-Jun-03 16:41 
GeneralMemory management Pin
Anonymous20-Jun-03 5:09
Anonymous20-Jun-03 5:09 
GeneralThis is not the way to do it. Pin
Joe O'Leary21-Jun-03 11:26
Joe O'Leary21-Jun-03 11:26 
On the contrary. What you have stated is not necessarily true at all. It depends upon the implementation of basic_string.

Consider the case of the implementation that comes along with Visual Studio .NET. This version has a fixed buffer size of 16 characters. Only if the string length exceeds this size does any dynamic memory allocation occur.

So using your example code with this particular implementation:

CStdString str("hello ! ");<br />
str += "I don't know ";<br />
str += "what this message means.";


There would NOT be any allocation or freeing of memory for either of the first two lines. Only for the third one.

This is far simpler and more portable than going to the trouble of writing and debugging your own string classes just to deal with such a relatively uncommon situation. New programmers do not have to learn how YOU tihnk a string class' interface should be, they can simply use the same basic_string interface they have always used with an optimized implementation that takes care of most of the common inefficiencies. Also, they can be far more confident of thoroughly debugged code as the user base for the basic_string<> implementation is guaranteed to be larger than the user base for your string class.

Furthermore, if memory allocation is a bottleneck in your program the thing to do is not to write your own string class. Instead you should write your own, specialized allocator<> template which optimizes away such problems. Supply this allocator as an argument to the instantiation of the basic_string (or to CStdStr) template. This is why the designers of the Standard C++ Library added the concept of allocators in the first place. It is whole lot easier and safer to use your own allocator<> than it is to try to use your own custom string class. Take my word for it, after 6 years of supporting this CStdString code base, there are few people more acutely aware of this fact than I.

Finally, the major performance bottleneck in most programs these days is not string manipulation. Even reasonably well-written code (with at least a passing thought given towards avoiding inefficient multiple concatenation steps such as those in the example) will have no problems with string-related memory allocation.

-Joe
GeneralExcellent, but warnings in VS7.1 Pin
TomM19-Jun-03 11:58
TomM19-Jun-03 11:58 
GeneralDo you have the latest version Pin
Joe O'Leary21-Jun-03 11:31
Joe O'Leary21-Jun-03 11:31 
GeneralRe: Do you have the latest version Pin
TomM22-Jun-03 9:44
TomM22-Jun-03 9:44 
GeneralRe: Do you have the latest version Pin
Navin11-Jul-03 10:07
Navin11-Jul-03 10:07 
GeneralRe: Do you have the latest version Pin
Joe O'Leary11-Jul-03 10:52
Joe O'Leary11-Jul-03 10:52 
GeneralFormat and Trim error Pin
Member 5267212-Jun-03 21:05
Member 5267212-Jun-03 21:05 
GeneralRe: Format and Trim error Pin
Joe O'Leary21-Jun-03 11:09
Joe O'Leary21-Jun-03 11:09 
Generalmy two cents... Pin
Philippe Bouteleux10-Jun-03 6:50
Philippe Bouteleux10-Jun-03 6:50 
GeneralRe: my two cents... Pin
Philippe Bouteleux10-Jun-03 6:53
Philippe Bouteleux10-Jun-03 6:53 
GeneralRe: my two cents... Pin
Joe O'Leary10-Jun-03 7:55
Joe O'Leary10-Jun-03 7:55 
Generalvswprintf preprocessor checks Pin
billca3-Jun-03 3:33
billca3-Jun-03 3:33 
GeneralExcellent -- this I LIKE Pin
Joe O'Leary3-Jun-03 18:01
Joe O'Leary3-Jun-03 18:01 
Generalvswprintf format spec Pin
billca3-Jun-03 3:17
billca3-Jun-03 3:17 
GeneralRe: vswprintf format spec Pin
Joe O'Leary3-Jun-03 17:54
Joe O'Leary3-Jun-03 17:54 
GeneralRe: vswprintf format spec Pin
Anonymous4-Jun-03 10:39
Anonymous4-Jun-03 10:39 
GeneralError on StdCodeCvt calls Pin
billca2-Jun-03 10:11
billca2-Jun-03 10:11 
GeneralRe: Error on StdCodeCvt calls Pin
Joe O'Leary3-Jun-03 17:42
Joe O'Leary3-Jun-03 17:42 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.