Adding strings in expressions

Web Site  Methods

 
Str::operator +
 
friend Str operator+(const Str& s1, const Str& s2)
friend Str operator+(const Str& s, const STRCHAR* lpsz)
friend Str operator+(const STRCHAR* lpsz, const Str& s)
friend Str operator+(const Str& s, STRCHAR ch)
friend Str operator+(STRCHAR ch, const Str& s)

These overloaded operators allow you to concatenate Str objects with other Str objects, C-style strings and single characters.  See the example below on typical usage of these:

   Str s1 = _T("John");
const STRCHAR* s2 = _T("Doe");

// Result: John Doe
Str s = s1 + _T(" ") + s2;

// Result: DoeJohn
s = s2 + s1;

// Result: Johnny
s = s1 + (STRCHAR) 'n' + (STRCHAR) 'y';

Note that we're typecasting the characters to STRCHAR.  Otherwise, in Unicode builds, the compiler will complain that it cannot resolve between the different operator overloads. This typecast does not affect performance since it produces no runtime code.

You must be careful when catenating strings with these operators! Novice users often make the following mistake:

   // WRONG!
someval1 = _T("John") + ' ' + some_str_obj;
someval2 = _T("John ") + _T("Doe") + some_str_obj;

Some of these expressions will not compile at all; some others, such as directly adding one const STRCHAR* to another, will compile and give unexpected results.  Always have in mind C++ operator precedence rules!  To be on the safe side, we recommend that when you add more than two text items in a single statement, make sure that no two non-Str object values are next to each other in the expression.  Or, when in doubt, you can typecast to Str:

   // Right
someval1 = _T("John") + Str((STRCHAR) ' ') + some_str_obj;
someval2 = Str(_T("John ")) + _T("Doe") + some_str_obj;

If you are looking to increase performance, we recommend that you use the += operator (or AddString / AddChar) methods -- they create less temporary objects "behind the scenes" and achieve the same effect, albeit with multiple statements.

 

See also: Adding to Strings