Click here to Skip to main content
16,005,697 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 4.1M   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: Problem with FormatV Pin
Anonymous11-Aug-02 8:25
Anonymous11-Aug-02 8:25 
GeneralRe: Problem with FormatV Pin
Joe O'Leary12-Aug-02 7:18
Joe O'Leary12-Aug-02 7:18 
GeneralRe: Problem with FormatV Pin
Anonymous12-Aug-02 13:29
Anonymous12-Aug-02 13:29 
GeneralHold it! Pin
Joe O'Leary12-Aug-02 13:39
Joe O'Leary12-Aug-02 13:39 
GeneralRe: Hold it! Pin
Anonymous13-Aug-02 19:09
Anonymous13-Aug-02 19:09 
GeneralRe: Hold it! Pin
Joe O'Leary14-Aug-02 4:05
Joe O'Leary14-Aug-02 4:05 
QuestionHow to make it faster Pin
mili9-Aug-02 6:53
mili9-Aug-02 6:53 
AnswerRe: How to make it faster Pin
Joe O'Leary9-Aug-02 7:19
Joe O'Leary9-Aug-02 7:19 
Like most overloaded operators, operator += is just syntactic sugar. A nicety to make for less typing. Semantically, it is exactly the same thing as the basic_string::append function.

I guess what you want is a version of the operator that would would (like your new Append function) allow you to specify the grow length. I guess that would technically be a ternary operator. It certainly wouldn't be operator +=.

An alternative might be to define a string class with a different std::allocator object that ensured memory would be allocated in the chunk size you specify. The basic_string template takes three arguments: A character type, a traits type, and an allocator type.

typedef basic_string<char, char_traits<char>, CMyAllocator> CMyString

where 'CMyAllocator' is a class defined by you for allocating characters in specific chunks. It would have to follow all the semantics of std::allocator.

One problem with this approach is that you would need to know that size at compile time, not runtime, unless you designed some changeable chunksize setting into your allocator that could be set at runtime. And furthermore, such a string class would not be interchangeable with std::string or std::wstring -- technically it's a different C++ type.

If you look at the definition of my template ('CStdStr') you'll see I did NOT put these argments into the definition. The only thing that one can specify to my template is the character type. I then derive from the 'default' implementation of basic_string, given that character type.

I did this for a couple of reasons:

1. It keeps the template name short in the debugging information.
2. I was trying to design something that was interchangeable with the existing specializations of basic_string, std::string and std::wstring

Still, it's easy enough to change. Just alter the template definition for CStdStr to take these extra two arguments and supply defaults for them, just like basic_string does. Your template should derive from basic_string but now supply all three of these arguments. Then write your own allocator with these capabilities and pass it in as the argument you want. Just remember, whatever class you instantiate from this will NOT have an "is-a" relationship with std::string or std::wstring.

Another approach might be to write your own version of operator+= for CStdString. It would check some changeable "grow-size" setting inside the CStdString object be appended. You would then provide member functions to change this setting. However this approach would either entail a) adding a new member variable to CStdString to hold this grow size -- very, very bad OR b)adding some global variable/static member to hold the setting -- also very bad.

Seems like an awful lot of work just to avoid calling reserve(), doesn't it? I'm all for syntactical niceties myself, but sometimes, you just gotta do the extra work, I think.


-Joe
AnswerRe: How to make it faster Pin
Philippe Mori19-Aug-02 14:15
Philippe Mori19-Aug-02 14:15 
AnswerRe: How to make it faster Pin
Anonymous9-Oct-02 22:28
Anonymous9-Oct-02 22:28 
GeneralVisual C++ 5.0 errors Pin
t7675-Aug-02 11:41
t7675-Aug-02 11:41 
GeneralRe: Visual C++ 5.0 errors Pin
Christian Graus5-Aug-02 12:12
protectorChristian Graus5-Aug-02 12:12 
GeneralCompiling with warning level 4 Pin
cagey4-Aug-02 10:56
cagey4-Aug-02 10:56 
GeneralRe: Compiling with warning level 4 Pin
Joe O'Leary4-Aug-02 15:41
Joe O'Leary4-Aug-02 15:41 
GeneralFinally! A fix for the Format() incompatability Pin
Joe O'Leary2-Jul-02 4:04
Joe O'Leary2-Jul-02 4:04 
Questionbcc combatibility? Pin
26-Jun-02 6:14
suss26-Jun-02 6:14 
AnswerRe: bcc combatibility? Pin
Joe O'Leary28-Jun-02 9:24
Joe O'Leary28-Jun-02 9:24 
GeneralLatest Version of code Pin
Joe O'Leary5-Jun-02 9:18
Joe O'Leary5-Jun-02 9:18 
QuestionCompiler problem or CStdString problem? Pin
Tony B.5-Jun-02 8:57
Tony B.5-Jun-02 8:57 
AnswerRe: Compiler problem or CStdString problem? Pin
Tony B.5-Jun-02 9:11
Tony B.5-Jun-02 9:11 
GeneralRe: Compiler problem or CStdString problem? Pin
Joe O'Leary5-Jun-02 9:16
Joe O'Leary5-Jun-02 9:16 
GeneralSolved my problem.. Pin
31-May-02 22:35
suss31-May-02 22:35 
GeneralRe: Solved my problem.. Pin
Joe O'Leary1-Jun-02 2:42
Joe O'Leary1-Jun-02 2:42 
QuestionA problem with one of the c'tors? Pin
Tony B.13-May-02 8:40
Tony B.13-May-02 8:40 
AnswerRe: A problem with one of the c'tors? Pin
Joe O'Leary13-May-02 16:12
Joe O'Leary13-May-02 16:12 

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.