My code often repeats a fragment:

TCHAR text[10] = {}; Convert(window, id1, text); 

I want to bring it into a separate function that will return a pointer to text .

 TCHAR* Foo(HWND window, int id) { TCHAR *text = new TCHAR[10]; Convert(window, id, text); return text; } 

When it will be necessary to free the memory, I do not know. Therefore, I used smart pointers:

 std::shared_ptr<TCHAR> Foo(HWND window, int id) { std::shared_ptr<TCHAR> text; Convert(window, id, text); //no suitable conversion function from //"std::shared_ptr<TCHAR>" to "TCHAR *" return text; } void Convert(HWND window, int ID, TCHAR* text, int size=10) { HWND handle = GetDlgItem(window, ID); GetWindowText(handle, text, size); } 

How to allocate memory for 10 elements and solve the problem with the conversion?

  • Write Convert(window, id, text.get()); . But with memory allocation, this problem will not solve - mymedia
  • You can use the std :: make_unique function, as in this example . But in any case, pay attention to the answer alexolut. - user227465

1 answer 1

In order for std::shared_ptr to work correctly with arrays, you need to set a custom deleter for it. Or, if your compiler supports c ++ 17, then you can parameterize std::shared_ptr array type, for example, TCHAR[] (thanks for the clarification of GreenDragon ). Otherwise, UB appears in the code, since the object will be released via delete , not delete[] as required after memory allocation via new[] .

In this case, general ownership is not required in principle, so you can use the specialization std::unique_ptr for arrays. However, knowing the specifics of your Convert function, it would be advisable to completely abandon manual memory management and smart pointers in particular, and use std::basic_string<TCHAR> , for example.

Those. I would suggest to convert Convert something like this:

 std::basic_string<TCHAR> Convert(HWND window, int ID) { HWND handle = GetDlgItem(window, ID); std::basic_string<TCHAR> ret(GetWindowTextLength(handle) + 1, _T(' ')); GetWindowText(handle, ret.data(), ret.size()); return ret; } 

But maybe here you need to take into account some other features of WinAPI .

  • In C ++ 17, std::shared_ptr added a constructor specialization for working with arrays. - user227465