Click here to Skip to main content
15,886,362 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 3.9M   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

 
GeneralUsing CStdString in a DLL Pin
Greg Strauss22-Mar-02 8:25
Greg Strauss22-Mar-02 8:25 
Generalcustom allocator Pin
Frederic My4-Jan-02 7:02
Frederic My4-Jan-02 7:02 
GeneralRe: custom allocator Pin
Frederic My4-Jan-02 7:07
Frederic My4-Jan-02 7:07 
GeneralRe: custom allocator Pin
4-Jan-02 10:33
suss4-Jan-02 10:33 
QuestionMaximum Size? Pin
James Spibey20-Dec-01 0:43
James Spibey20-Dec-01 0:43 
AnswerRe: Maximum Size? Pin
Joe O'Leary22-Feb-02 8:04
Joe O'Leary22-Feb-02 8:04 
GeneralBug with recursion Pin
19-Sep-01 2:02
suss19-Sep-01 2:02 
GeneralRe: Bug with recursion Pin
19-Sep-01 4:20
suss19-Sep-01 4:20 
Wow! Very sneaky bug. You're right, it is a bug in the implementation of the Standard C++ Library that comes with Visual C++. The good news is that the latest implementation of the Dinkumware Standard C++ Library has fixed this bug. If you are running Visual C++ and you buy the next version it will be fixed. It is also fixed in the commercially available Dinkumware release too, if you just can't wait.

I don't know if STLPort has the problem or has fixed it. I didn't have time to test.

For the record (since you didn't mention it) the effect is that around the fourth time through the loop, the string becomes corrupted and the program crashes

What happens is that at around the 4th time through the loop, the string object realizes it doesn't have enough capacity to double it's size yet *again* so it grows -- it adds some more capacity.

Unfortunately, it has already called c_str() on the string being added. Normally this wouldn't matter but since the string being added is itself, that means it has a direct pointer to it's own string buffer that is going to become invalid once it reallocates its internal memory.

In the meantime, a workaround is to perform checks before adding to see if

1. The string being added lies within it's boundaries
2. It is going to need to grow capacity

If so, the string should either grow first, or make a copy of what's being added (to a separate string object) before growing. Obviously this must be done in the library, not in my derived class. You need an update, I'm afraid.

In the meantime, I have posted an updated version of StdString which will make your program run properly. However, it will only work for CStdString objects. It will *not* fix this problem if you were to use simple std::string or std::wstring objects. Thus, it's only a band-aid. The true fix is to update your Standard C++ Library

You can get the fix here

http://home.earthlink.net/~jmoleary/code/StdString.zip

Thanks for the report.

Joe O'


Joe O'Leary
GeneralRe: Bug with recursion Pin
30-Jun-02 12:35
suss30-Jun-02 12:35 
GeneralRe: Bug with recursion Pin
Joe O'Leary30-Jun-02 15:51
Joe O'Leary30-Jun-02 15:51 
GeneralExceptional Work Pin
27-Aug-01 13:07
suss27-Aug-01 13:07 
GeneralYou rock, dude. Pin
Jon Sagara10-Aug-01 19:31
Jon Sagara10-Aug-01 19:31 
GeneralRe: You rock, dude. Pin
10-Aug-01 23:06
suss10-Aug-01 23:06 
GeneralProblem with Format Pin
12-Jul-01 23:25
suss12-Jul-01 23:25 
GeneralRe: Problem with Format Pin
13-Jul-01 4:47
suss13-Jul-01 4:47 
GeneralRe: Problem with Format Pin
peterchen2-Dec-01 2:29
peterchen2-Dec-01 2:29 
GeneralMemory Leak! Pin
29-May-01 19:33
suss29-May-01 19:33 
GeneralRe: Memory Leak! Pin
Christian Graus29-May-01 19:58
protectorChristian Graus29-May-01 19:58 
GeneralRe: Memory Leak! Pin
29-May-01 20:01
suss29-May-01 20:01 
GeneralHelp for an other article Pin
Arnaud Brejeon29-May-01 15:53
Arnaud Brejeon29-May-01 15:53 
GeneralRe: Help for an other article Pin
29-May-01 19:39
suss29-May-01 19:39 
GeneralRe: Help for an other article Pin
Arnaud Brejeon29-May-01 20:37
Arnaud Brejeon29-May-01 20:37 
Generaloperator[] and other incompatibilities Pin
William E. Kempf29-May-01 4:17
William E. Kempf29-May-01 4:17 
GeneralRe: operator[] and other incompatibilities Pin
Tomasz Sowinski29-May-01 4:36
Tomasz Sowinski29-May-01 4:36 
GeneralRe: operator[] and other incompatibilities Pin
William E. Kempf29-May-01 4:39
William E. Kempf29-May-01 4:39 

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.