Reputation: 15718
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.
Upvotes: 1
Views: 7748
Reputation: 55887
Yes this is OK, since CString
has conversion operator to LPCTSTR
. reference to operator
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
.
Upvotes: 2
Reputation: 36896
Yes this is OK. According to the documentation you just need to make sure that you don't modify the string during the duration of the returned pointer, which your code is doing fine.
This is basically the CString
equivalent of std::string::c_str()
.
Usually though you don't need to explicitly use the cast as your code does. The only reason I can think you need to do that is if you're converting to yet another type, for example if SomeFunction
is defined as
void SomeFunction(const std::basic_string<TCHAR>& str);
In that case there is no implicit conversion from CString
to std::basic_string<TCHAR>
so you need to use LPCTSTR
as an in-between.
Upvotes: 1