简体   繁体   中英

c++ type conversion: error C2440: 'initializing' : cannot convert from 'HRESULT' to 'std::basic_string<_Elem,_Traits,_Alloc>'

I tried this in Visual studios 2012:

TCHAR szPath[MAX_PATH];
std::wstring applicationdatafolder = SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, 0, szPath);
MessageBox(NULL, applicationdatafolder, NULL, MB_OK); 

I got those errors:

Error C2440: 'initializing' : cannot convert from 'HRESULT' to 'std::basic_string<_Elem,_Traits,_Alloc>' (2nd row)

Error C2664: 'MessageBoxW' : cannot convert parameter 2 from 'std::wstring' to 'LPCWSTR' (3rd row)

the SHGetFolderPath function do return a HRESULT to show if everything went right. The actual "string" will be stored where last parameter points to: ergo into szPath . Now what you want is to construct the string from this char array via std::wstring applicationdatafolder (szPath) and use it

addendum for Qs emerged in comments

wstring foo(bar) vs wstring foo = bar afaik (feel free to edit if im wrong) the usage of the copy constructor is more efficient:

wstring foo(bar)

  1. creates a new wstring but knows what will be stored
  2. allocates enough memory for content from bar
  3. copies content from bar

wstring foo = bar is essentialy wstring foo(); foo = bar; wstring foo(); foo = bar;

  1. creates a new empty wstring ( wstring foo calls the default constructor without params)
  2. allocates 1 byte (only line ending symbol will be stored)
  3. places the line ending there
  4. calls operator=
  5. frees the memory allocated in 2.
  6. allocates enough place to store content from bar
  7. copies the content from bar

of course the compiler will probably recognize the redundant steps and optimize the code, but by using the former version we write efficient code in first place and don't rely on compiler optimiziation

also the former version is somewhat clearer as it reads as "make a wstring named foo from bar " and latter is "make a wstring named foo and assign bar to it". Pay attention to the fakt bar can be of some arbitrary type and though compiler understands what you want, it may seem look strange to have a string and some mywierdtype in an assignment.

TCHAR szPath[MAX_PATH];
SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, 0, szPath);
std::wstring applicationdatafolder(szPath);
MessageBox(NULL, applicationdatafolder.c_str(), NULL, MB_OK); 

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