Reputation: 1471
I have a class that needs to save a file, the constructor gets a LPWSTR called fullPath, then i tried to do this (curPath is a LPCWSTR class variable):
curPath = (std::wstring(fullPath) + L".ip").c_str();
but it ends up being gibberish. Meanwhile this works:
auto cp = std::wstring(fullPath) + L".ip";
curPath = cs.c_str();
while it seems to me they should essentially do the same thing. Whats up with that?
Upvotes: 1
Views: 138
Reputation: 2624
The temporary std::wstring created by the expression (std::wstring(fullPath) + L".ip")
will be destroyed after the expression is evaluated.
Using the internal memory of this temporary (exposed by c_str) is undefined behavior and a bug.
In the second expression you keep the result in the auto variable cp. So until the end of the current scope you are allowed to use the internal memory of variable cp. Once the scope ends cp is will be destroyed and its memory released.
Upvotes: 2