Re: Lifetime of temporaries?
Jorgen Grahn wrote:
I should know this, but ...
Is this code safe?
You need to define "safe". I am not certain it's a standard term.
std::string foo();
OK, 'foo' is a function returing a string.
std::printf("%s", foo().c_str());
This is an expression statement, a function call to 'std::printf' with
two arguments. The temporary returned by 'foo' lives until the end of
the full expression (here: the semicolon). The pointer 'c_str' returns
*also* lives as long as the [temporary] object that has produced it.
Or is my temporary std::string destroyed before printf()
is done with it?
'printf' doesn't actually do anything with your temporary. It needs the
pointer your temporary returns. And actually the pointer can live less
than the temporary...
Background:
I'm sitting with a whole bunch of classes and (for now) only a
printf-like interface for printing logs/debug info. I was thinking
about
- implementing ostream << foo as usual,
- have a 'template<T> std:string to_string(const T&)' based on it
- log using the slightly ugly syntax
log("error in %s: %s",
to_string(foo).c_str(),
to_string(bar).c_str());
It's ugly and extremely wasteful, but I want to define the output
format in *one* place for each class -- not in every place where I might
want to print it.
Seems like you're on your way to a satisfactory solution.
Good luck!
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask