简体   繁体   中英

why does &(std::to_wstring()) return an empty string?

I'm trying to convert an int to a wstring* using the std::to_wstring function in a C++/CX app for Windows.

The following does NOT work:

wstring* turn = &(to_wstring(50));               //the value of *turn is ""

This however does:

wstring tu = to_wstring(50);
wstring* turn = &tu;                             //the value of *turn is "50"

Could someone explain why? Shouldn't both code snippets show the exact same behaviour?

to_wstring(50) is a temporary. Temporaries are destroyed at the end of the full-expression ( ie , just after the semicolon). So after the first snippet runs, turn points to some memory that no longer contains a valid std::wstring , since it has already been destroyed.

In the second snippet, the temporary to_wstring(50) is copied into the variable tu . The temporary is destroyed, but tu is not, since it's still in scope.

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