简体   繁体   中英

C++ Compile Error in Visual Studio 2012: LPCWSTR and wstring

The following code compiles in Visual Studio 2010 but fails to compile in the Visual Studio 2012 RC.

#include <string>

// Windows stuffs
typedef __nullterminated const wchar_t *LPCWSTR;

class CTestObj {
public:
    CTestObj() {m_tmp = L"default";};

    operator LPCWSTR()  { return m_tmp.c_str(); }       // returns const wchar_t*
    operator std::wstring() const { return m_tmp; }     // returns std::wstring

protected:
    std::wstring m_tmp;
};


int _tmain(int argc, _TCHAR* argv[])
{
    CTestObj x;
    std::wstring strval = (std::wstring) x;

    return 0;
}

The error returned is:

error C2440: 'type cast' : cannot convert from 'CTestObj' to 'std::wstring'
No constructor could take the source type, or constructor overload resolution was ambiguous

I've already realized that commenting out either of the conversion operators fixes the compile problem. I just want to understand:

  1. What 's going on under the hood to cause this
  2. Why this compiles in VS2010 and not in VS2012? Is it because of a C++11 change?

If I'm understanding the logic under the hood, the operator overload is trying to copy the code and the object every time you cast. Therefore, you need to return it as a reference instead of attempting to return a new object based on the field. The line:

operator std::wstring() const { return m_tmp; }

should be:

operator std::wstring&() { return m_tmp; }

The following compiles and runs as expected.

#include <string>

// Windows stuffs
typedef __nullterminated const wchar_t *LPCWSTR;

class CTestObj {
public:
    CTestObj() {m_tmp = L"default";};

    operator LPCWSTR()  { return m_tmp.c_str(); }       // returns const wchar_t*
    operator std::wstring&() { return m_tmp; }     // returns std::wstring

protected:
    std::wstring m_tmp;
};


int main()
{
    CTestObj x;
    std::wstring strval = (std::wstring) x;
    wprintf(L"%s\n", strval.c_str());

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM