Home > Software engineering >  How to return a value from a function of type `LPCTSTR`?
How to return a value from a function of type `LPCTSTR`?

Time:08-29

What is the 'proper' way to return wintitle from the function?

The way i did the compiler is pointing this warning: warning C4172: returning address of local variable or temporary: wintitle

LPCTSTR WinGetTitle(HWND hWnd)
{
    TCHAR wintitle[250];
    GetWindowText(hWnd, wintitle, GetWindowTextLength(hWnd)   1);
    return wintitle;
}

LPCTSTR wintitle;    
wintitle = WinGetTitle(hWnd);

CodePudding user response:

The compiler diagnostic is spot on: wintitle is an object with automatic storage duration. When the function returns, it's memory is automatically freed, leaving the returned pointer dangling.

If you do wish (you probably don't) to return a pointer, you'll have to have it point into memory that outlives the function call. That's either a pointer into a buffer with static storage duration, or a heap allocation. Neither is particularly useful (the former needs to be fixed size, and the latter puts the burden of releasing the memory on the caller, which usually doesn't know how to).

It is far more practical to return an object that manages its memory automatically. Using a std::wstring is the canonical solution. You can instantiate an object, fill it with contents, and then return it to the caller:

std::wstring WinGetTitle(HWND hWnd)
{
    std::wstring wintitle;
    auto const len = ::GetWindowTextLengthW(hWnd);
    if (len > 0) {
        wintitle.resize(static_cast<size_t>(len));
        GetWindowTextW(hWnd, wintitle.data(), len   1);
    }
    return wintitle;
}

If you need to get an LPCWSTR pointer to pass it into other API calls, you can use std::wstring's c_str() member.

This requires C 17 to return a pointer to non-const from data(). Also note that I omitted using generic-text mappings. Those aren't useful, unless you're targeting Win9x (which has been out of support for a while now).

  • Related