Reputation: 777
I have a CString pointer and it is being compared to a TCHAR in the following way:
if(srtTest[i] == _T('\n'))
//do something
where strTest is a CString* strTest;
I just wonder if this is correct, considering it is not a TCHAR-pointer. It compiles ok. This code is very old and no one seems to have complained about it, makes me wonder though.
Upvotes: 1
Views: 740
Reputation: 9393
Yes, it's ok (assuming strTest
is a valid pointer and i
is a valid index). Since strTest
is a CString*
, strTest[i]
is a CString
. And there is a free operator==
overload that accepts a const CString&
as param1 and an LPCTSTR
as param2 and then does what you'd expect.
The MSDN documentation is here. The second overload is the one that matters:
BOOL operator ==( const CString& s1, LPCTSTR s2 );
(the documentation is out of date and the signature I see when I trace into the actual code is different, but the effect is the same)
MarkRansom alerted me to the fact that your code compares strTest[i]
to a character rather than to a string. That's still ok, because there is also an operator==
overload that takes CString
/char
. It's not listed in the documentation I linked to, but here's what the actual code looks like in the VS2012 version:
friend bool operator==(
_In_ const CStringT& str1,
_In_ XCHAR ch2) throw()
{
return( (str1.GetLength() == 1) && (str1[0] == ch2) );
}
Since it's not listed in the outdated documentation, this function presumably did not always exist. However, CString
has an implicit constructor that takes a TCHAR
. I assume that in VC++ versions that predate the above, a CString
would be implicitly constructed from _T('\n')
and then used in a call to the CString
/CString
overload of operator==
.
Upvotes: 4
Reputation: 1350
The MSDN documentation on CString operators is old. Very old. They do provide operator==
for LPCTSTR
, but that is defined as a const TCHAR*
. _T('\n')
is a TCHAR
, not a TCHAR*
so none of these apply. Yet it seems to work...
In cstringt.h, I see (I'm using VS 2010):
friend bool operator==(
_In_ const CStringT& str1,
_In_ XCHAR ch2) throw()
{
return( (str1.GetLength() == 1) && (str1[0] == ch2) );
}
This article explains simply what an XCHAR
is. Basically a TCHAR
. So here, presumably, is the bool operator==(const CString&, TCHAR ch)
you are using.
Upvotes: 2