Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?
like image 544
jqcAngel Avatar asked Jun 01 '12 00:06

jqcAngel


1 Answers

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;
}
like image 162
Qix - MONICA WAS MISTREATED Avatar answered Nov 08 '22 06:11

Qix - MONICA WAS MISTREATED