As you seem to have gathered, LPCTSTR
and TCHAR
are basically defined as following (LPCTSTR
would be read long pointer to constant TCHAR
):
#ifdef _UNICODE
typedef wchar_t TCHAR;
#else
typedef char TCHAR;
#endif // _UNICODE
typedef const TCHAR* LPCTSTR;
So you can initialize a LPCTSTR
variable as you would a const wchar_t*
or a const char*
variable, e.g. for unicode:
LPCTSTR lpszUnicode = L"Test String";
And for ASCII/MultiByte:
LPCTSTR lpszMultibyte = "Test String";
There are however, useful macros when working with the WinAPI: _T("x")
and TEXT("x")
, which both expand to L"x"
(if your project is set for Unicode) or "x"
(if your project properties are set for Multibyte). So for instance, you could use:
LPCTSTR lpszTest = _T("Test String");
LPCTSTR lpszTest2 = TEXT("Test String 2");
And this will compile under either unicode or multibyte project settings. As for the reason that there are multiple macros expanding to the same thing, check out this blog post.
You can also do what you are doing by dynamically allocating memory as you have done, so for instance:
LPTSTR lpszDynamic = new TCHAR[100];
// Do something with lpszDynamic
delete[] lpszDynamic;
However, if you are finding yourself dynamically allocating memory often like this, it might be better to use string classes, such as CString
or std::string
/std::wstring
(I often have the following in my MFC/WinAPI projects):
namespace std {
#ifdef _UNICODE
typedef wstring tstring;
#else
typedef string tstring;
#endif // _UNICODE
};