Pointer to the temporary string

  • A+
Category:Languages

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"

 


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.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: