Reputation: 147
we have the following functions:
std::wstring f(const std::string& ref){
return boost::locale::conv::utf_to_utf<wchar_t>(s);
}
const f2(LPCWSTR p){
// use p
}
Is it safe to call:
std::string s = "x";
f2(f(s).c_str());
My doubt is raised by the fact that f(s)
returns a temporary object and f2
takes a pointer to it.
Dr. Memory points that it is "unaddressable access". When I replace it with:
std::string s = "x";
std::wstring s2 = f(s);
f2(s2.c_str());
Dr. Memory does not point "unaddressable access"
Upvotes: 3
Views: 130
Reputation: 16243
The temporary will remain valid for the duration of the full expression f2(f(s).c_str());
- ie. that includes the f2
function call.
This assumes that f2
will not store the pointer to be used after the function ends.
Upvotes: 5
Reputation: 170143
So long as f2
doesn't store the pointer for later use, it's all perfectly fine.
Any temporary created during the evaluation of a sub-expression, exists until the end of the complete expression it appears in. So f(s).c_str()
will be a valid pointer for the duration of the call to f2
.
Upvotes: 7