4

I've come across multiple instance of this pattern (with boost::filesystem only used as example):

boost::filesystem::path path = ...;
someFunctionTakingCStrings(path.string().c_str());

where

const std::string path::string() const
{
  std::string tmp = ...
  return tmp;
}

Although I have never experienced problem with this pattern, I was wondering when the string returned by sting() is destroyed and whether the code accessing the c_str() is safe as the c_str() lifetime is bound to std::string lifetime.

Community
  • 1
  • 1
PhilLab
  • 4,777
  • 1
  • 25
  • 77

1 Answers1

6

someFunctionTakingCStrings(path.string().c_str()); is safe since the standard guarantees that the lifetime of the anonymous temporary path.string() survives the function call. So the pointer returned by c_str() is a valid parameter for someFunctionTakingCStrings.

const std::string path::string() const is safe since, conceptually, you are returning a value copy of tmp, although in practice a compiler will optimise out the value copy (a process called named return value optimisation).

Something like const std::string& path::string() const with the same function body as the one you have would not be defined (since the reference would dangle), and

const char* ub_server()
{
    std::string s = "Hello";
    return s.c_str();
}

is also undefined, as s is out of scope by the time the function returns.

Finally, note that taking a pointer to an anonymous temporary as a parameter in a function call is not allowed in standard C++ although annoyingly, Visual C++ allows it as an extension.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • thanks. A quick follow-up: So, ``functionTakingPointer(&path.string())`` would also be safe? – PhilLab Dec 20 '16 at 11:00
  • @PhilLab: No it's unsafe in standard C++. I've put that at the end of the answer. – Bathsheba Dec 20 '16 at 11:02
  • hm, then I have not understood the lifetime of path.string() completely. Or are anonymous temporaries a whole chapter on their own concerning memory management? – PhilLab Dec 20 '16 at 11:10
  • 1
    @PhilLab: That's pretty much the case, yes. Some nice reading for you over Christmas. – Bathsheba Dec 20 '16 at 11:16