2

Lets say I have a function that takes a string as a char*

void GiveMeFileName(const char* fileName)

and I call it like this

std::string folderName("C:\\myFolder\\");
GiveMeFileName((folderName + "file.dat").c_str());

As far as I can tell its working fine but as to why is a bit shaky in my head.

When I add the const char* to the std:::string, it creates a new string which I call c_str() upon to pass the pointer to the function. Is it possible that after I call the c_str() and it resolves into a pointer, the temporarily created string gets deleted and what I'm passing is in fact a pointer to the remnant of an object and thus could potentially fail?

user81993
  • 6,167
  • 6
  • 32
  • 64
  • It is fine. I don't have reference but the lifetime of the temp string is at end of semi-colon – Bryan Chen Mar 14 '16 at 08:27
  • Yes, it's fine. If the values created in a parameter list went away before the function they were passed to finished, that would be pretty worthless. – xaxxon Mar 14 '16 at 08:29
  • Just don't store `fileName` anywhere which outlives `GiveMeFileName`. – TartanLlama Mar 14 '16 at 08:30

0 Answers0