c++linuxwindowswidecharwchar

Duplicating wide-character string


I am trying to create an application in which I have a function where I am trying to duplicate a wide character string. I am currently using _wcsdup(), since it is a Windows application and everything is working fine for me. But I need to create a multi-platform function, so _wcsdup() (which is a Windows function) will not work out for me.

Now, my code looks something like this:

wchar_t* out = _wcsdup(wstring.str().c_str());

where wstring is a string stream.

Now, I am looking for a common function for both Windows and Linux to make this function work properly.


Solution

  • The standard cross-platform equivalent would be to allocate/free a wchar_t[] buffer using new[]/delete[] (or, if absolutely needed, malloc()/free() to mirror the behavior of _wcsdup()), using std::copy() or std::memcpy() to copy characters from wstring into that buffer, eg:

    std::wstring w = wstring.str();
    wchar_t* out = new wchar_t[w.size()+1];
    std::copy(w.begin(), w.end(), out);
    w[w.size()] = L'\0';
    ...
    delete[] out;
    
    /*
    std::wstring w = wstring.str();
    wchar_t* out = (wchar_t*) malloc((w.size() + 1) * sizeof(wchar_t));
    std::copy(w.begin(), w.end(), out);
    w[w.size()] = L'\0';
    ...
    free(out);
    */
    
    std::wstring w = wstring.str();
    size_t size = w.size() + 1;
    wchar_t* out = new wchar_t[size];
    std::memcpy(out, w.c_str(), size * sizeof(wchar_t));
    ...
    delete[] out;
    
    /*
    std::wstring w = wstring.str();
    size_t size = (w.size() + 1) * sizeof(wchar_t);
    wchar_t* out = (wchar_t*) malloc(size);
    std::memcpy(out, w.c_str(), size);
    ...
    free(out);
    */
    

    But, either way, since str() returns a std::wstring to begin with, you are better off simply sticking with std::wstring instead of using wchar_t* at all:

    std::wstring out = wstring.str();
    

    You can use out.c_str() or out.data() if you ever need a (const) wchar_t*, such as when passing out to C-style functions that take null-terminated string pointers.