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; }
source share