In the first example you are getting the address of a temporary. After that line has executed that wstring
object you assigned myString
to isn't available anymore (these are so called rvalue
s by the way). I think it should be obvious that in the second example you have a real object (a lvalue
which is valid as long as it doesnt run ot of scope.
To overcome this limitation with the scope you can directly create a wstring
on the heap, this might better suite your situation but without further information this is hard to tell:
std::wstring* myString = new std::wstring(L"my basic sentence" + some_wstring_var + L"\r\n");
The newly created wstring
will me initialized with the contents of the temporary rvalue.
Just do not forget to destroy the pointer after you are done with it.
With C++11 things have complicated so temporaries can be reused more often for performance reasons. But this topic is very though and will exceed this question. I just wanted to mention it because it might interesst you aswell. For a really great explanation take a look at this SO question: What are move semantics?