Reputation: 14504
I'm trying to convert an int
to a wstring*
using the std::to_wstring
function in a C++/CX app for Windows.
wstring* turn = &(to_wstring(50)); //the value of *turn is ""
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?
Upvotes: 0
Views: 261
Reputation: 119382
to_wstring(50)
is a temporary. Temporaries are destroyed at the end of the full-expression (i.e., 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.
Upvotes: 2