user566
user566

Reputation: 97

How to convert LPTSTR to LPCTSTR&

The function parameter is LPCTSTR&.

I have to pass LPTSTR variable as LPCTSTR&.

How to convert LPTSTR to LPCTSTR&.

Thanks in advance.

Upvotes: 0

Views: 356

Answers (1)

ferosekhanj
ferosekhanj

Reputation: 1074

From my old C++ experience, you are trying to pass a pointer to a const string by reference. The compiler thinks you are going to change the pointer value. So you have 2 options

  1. Make the parameter const so compiler can accept the LPSTR.
  2. Or create a LPCTSTR pointer (an lvalue that can be changed) and pass it.

I have to tried to explain it in the following code snippet. I used VS 2017 + Windows 7 + SDK 10

void Foo(LPCTSTR &str)
{
    std::wcout << str;
    str = _T("World");
}

void FooConst(LPCTSTR const &str)
{
    std::wcout << str;
    //str = _T("World"); will give error
}

int main()
{
    LPTSTR str = new TCHAR[10];
    LPCTSTR str1 = str;
    lstrcpy(str, _T("Hello"));

//  Foo(str);// Error E0434 a reference of type "LPCTSTR &" (not const - qualified) cannot be initialized with a value of type "LPTSTR" HelloCpp2017
//  Foo(static_cast<LPCTSTR>(str));// Error(active) E0461   initial value of reference to non - const must be an lvalue HelloCpp2017    d : \jfk\samples\cpp\HelloCpp2017\HelloCpp2017\HelloCpp2017.cpp 19

    // Tell compiler you will not change the passed pointer
    FooConst(str);

    // Or provide a lvalue pointer that can be changed
    Foo(str1);

    std::wcout << str1;

    return 0;
}

Upvotes: 3

Related Questions