CString to TCHAR

snoopy picture snoopy · Aug 9, 2012 · Viewed 7.3k times · Source

Today after a long time I've seen this conversion:

void SomeFunction( LPCTSTR szText ) ...


CString str;
str.Format( "A Simple Sentence" );
SomeFunction( LPCTSTR( str ) );

It compiles OK. Any explanations about this conversion?

It seems mostly ok, because I don't need to use GetBuffer and release it later, nor create a new LPTSTR with the length of the string.

Answer

ForEveR picture ForEveR · Aug 9, 2012

Yes this is OK, since CString has conversion operator to LPCTSTR. reference to operator

msdn

The C++ compiler automatically applies the conversion function defined for the CString class that converts a CString to an LPCTSTR.

So, you don't need use explicitly conversion to LPCTSTR.