Search code examples
c++windowsstdvector

Getting WCHAR back when using vector or make_unique in C++?


In my Windows code in Visual Studio 2019, I'm trying to understand/best way to get a string from another function using vector and make_unique.

It's straightforward to call GetText() when using new/delete, but C26409 says "Avoid calling new and delete explicitly, use std::make_unique instead(r.11)".

C26409 recommends converting to a std::unique_ptr (or a vector), of which I've done both below, but how do I use the existing function GetText() for all declarations (new/vector/make_unique)?

Secondly, is there another way I should be rewriting GetText() so it can take as input a (new, vector, or make_unique)?

Here is my sample code.

#include <windows.h>
#include <strsafe.h>
#include <vector>
#include <memory>

void GetText(WCHAR **sText, DWORD dwTextSize)
{
    StringCchPrintfW(*sText, dwTextSize, L"this is a %s", L"test");
}

int main()
{
    auto *sResult = new WCHAR[256];
    StringCchPrintfW(sResult, 256, L"this is a %s", L"test");
    GetText(&sResult, 256);
    delete[] sResult;

    std::vector<WCHAR> sResult2(256);
    StringCchPrintfW(sResult2.data(), sResult2.size(), L"this is a %s", L"test");
    //GetText(&sResult2.data(), 256);

    auto sResult3 = std::make_unique<WCHAR[]>(256);
    StringCchPrintfW(sResult3.get(), 256, L"this is a %s", L"test");
    //GetText(&sResult3.get(), 256);    
}

Solution

  • Rewrite your function like this

    void GetText(WCHAR *sText, DWORD dwTextSize)
    {
        StringCchPrintfW(sText, dwTextSize, L"this is a %s", L"test");
    }
    

    Use it like this

    WCHAR *sResult = new WCHAR[256];
    GetText(sResult, 256);
    delete[] sResult;
    
    std::vector<WCHAR> sResult2(256);
    GetText(sResult2.data(), 256);
    
    auto sResult3 = std::make_unique<WCHAR[]>(256);
    GetText(sResult3.get(), 256);    
    

    Your function had a unnecessary level of indirection (WCHAR** instead of WCHAR*). Once that is removed the function becomes trivial to use with all three of your data types.