0

I am wondering is this adequate enough to use in a production codebase?

std::wstring s2w(const std::string& s)
{
    std::wstring ws;
    ws.assign(s.begin(), s.end());
    return ws;
}

std::string w2s(const std::wstring& w)
{
    std::string s;
    s.assign(w.begin(), w.end());
    return s;
}
2
  • 2
    AFAIK, no, it isn't adequate, because it doesn't do any conversion (only narrowing). You'll have to do a real conversion between the narrow string encoding and the wide string encoding. For example, using codecvt<wchar_t,char,mbstate_t>, in C++11 probably combined with wstring_convert. Commented Aug 8, 2013 at 12:35
  • Similar question: stackoverflow.com/questions/7141260/… Commented Aug 8, 2013 at 12:40

1 Answer 1

0

No, this is not sufficient.

Consider a wstring that contains the following characters (numeric values used for clarity) { 0x41, 0x1243, 0x62 } (That's 'A', followed by ETHIOPIC SYLLABLE QAA, followed by 'b' if you're using Unicode).

Converting to a string using your routine would result in a sequence containing { 0x41, 0x43, 0x42 }, or 'ACb'. Probably not what you expected - or wanted.

As DyP said - you're not doing any conversion, only narrowing.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.