Construcción
En lugar de escribir:string s;
...
s = "abc"
Usar:string s( "abc" );
La primera línea crea un objeto vacío usando el constructor por defecto y luego llama al operador de asignación. La segunda forma hace sólo una llamada al constructor con un argumento. Es mucho más rápido.
Concatenación
Use the assignment composite operators (like in a += b) instead of simple operators combined with assignment operators (like in a = a + b).
For example, instead of the following code:string s1( "abc" );
string s2 = s1 + " " + s1;
Write the following code:string s1( "abc" );
string s2 = s1;
s2 += " ";
s2 += s1;
Typically a simple operator creates a temporary object. In the example, the operator + creates temporary strings, whose creation and destruction require much time.
On the contrary, the equivalent code using the += operator do not create temporary objects.
CString Argument Passing
Fuente: MFC Library Reference (http://msdn.microsoft.com/en-us/library/acttytz3.aspx)
Strings as Function Inputs
If a string is an input to a function, in most cases it is best to declare the string function parameter as LPCTSTR. Convert to a CString object as necessary within the function using constructors and assignment operators. If the string contents are to be changed by a function, declare the parameter as a nonconstant CString reference (CString&).
Para declarar un argumento con referencias constantes sería de esta forma: void foo( const CString & s )
{
...
}
Strings as Function Outputs
Normally you can return CString objects from functions because CString objects follow value semantics like primitive types. To return a read-only string, use a constant CString reference (const CString&). The following example illustrates the use of CString parameters and return types:
class CName : public CObject
{
private:
CString m_firstName;
TCHAR m_middleInit;
CString m_lastName;
public:
CName() {}
void SetData(LPCTSTR fn, const TCHAR mi, LPCTSTR ln)
{
m_firstName = fn;
m_middleInit = mi;
m_lastName = ln;
}
void GetData(CString& cfn, TCHAR& mi, CString& cln)
{
cfn = m_firstName;
mi = m_middleInit;
cln = m_lastName;
}
CString GetLastName()
{
return m_lastName;
}
};
CName name;
CString last, first;
TCHAR middle;
name.SetData(_T("John"), 'Q', _T("Public"));
ASSERT(name.GetLastName() == _T("Public"));
name.GetData(first, middle, last);
ASSERT((first == _T("John")) && (last == _T("Public")));
_________________________________________________________________________________________________________
CPlusPlusApuntesC
[camelCaseWordsEnabled: false]