C ++ compilation error in Visual Studio 2012: LPCWSTR and wstring

The following code compiles in Visual Studio 2010, but does not compile in 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; } 

Error returned:

error C2440: 'cast type': cannot convert from 'CTestObj' to 'std::wstring'
The constructor cannot use the source type, or the resolution of the constructor overload was ambiguous.

I already realized that commenting on any of the conversion statements fixes the compilation problem. I just want to understand:

  • What happens under the hood to trigger this.
  • Why is this compiling in VS2010 and not in VS2012? Is this due to a change in C ++ 11?
+6
source share
1 answer

If I understand the logic under the hood, operator overloading tries to copy the code and the object with every click. Therefore, you need to return it as a link instead of trying to return a new object based on the field. Line:

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

it 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; } 
+1
source

Source: https://habr.com/ru/post/917136/


All Articles