How can CString be passed to format string %s?

前端 未结 4 472
孤街浪徒
孤街浪徒 2020-12-02 01:25
class MyString
{
public:
    MyString(const std::wstring& s2)
    {
        s = s2;
    }

    operator LPCWSTR() const
    {
        return s.c_str();
    }
pri         


        
4条回答
  •  一整个雨季
    2020-12-02 02:08

        wprintf(L"%s\n", (LPCWSTR)cstring); // Okay. It's been cast to a const wchar_t*.
        wprintf(L"%s\n", cstring); // UNDEFINED BEHAVIOUR
        wprintf(L"%s\n", (LPCWSTR)s); // Okay, it's a const wchar_t*.
        wprintf(L"%s\n", s); // UNDEFINED BEHAVIOUR
    

    The only thing you can pass to this function for %s is a const wchar_t*. Anything else is undefined behaviour. Passing the CString just happens to work.

    There's a reason that iostream was developed in C++, and it's because these variable-argument functions are horrifically unsafe, and shoud never be used. Oh, and CString is pretty much a sin too for plenty of reasons, stick to std::wstring and cout/wcout wherever you can.

提交回复
热议问题