#include <cstdio>
#include <string>
std::string foo()
{
return "Hello, World!";
}
int main()
{
printf( "%s\n", foo().c_str() );
}
Asked
Active
Viewed 89 times
1

qdii
- 12,505
- 10
- 59
- 116
-
4Yes. It is long enough. – R Sahu Feb 10 '15 at 22:36
-
http://stackoverflow.com/questions/584824/ – Drew Dormann Feb 10 '15 at 22:40
2 Answers
1
Yes, it is long enough. The string literal will cease to exist as the function returns, but at that point it has already been copied to a temporary std::string
. That string will be copied (or will be created at the call site through copy elision) to the calling code. The resulting string will exist until the end of the expression, long enough to be passed to printf
.

Mark Ransom
- 299,747
- 42
- 398
- 622
-
2`The string literal will cease to exist as the function returns`, no it will not, string literals have static storage duration. It is irrelevant for the question tho. – sbabbi Feb 10 '15 at 22:52
0
return "Hello, World!";
Returns a std::string
(implicitely) constructed from the c-style string literal, and that can be considered as static
in the function's scope.
The temporary std::string
's lifetime can be considered stable after returning from foo()
in this case. It will be copied, or at least being moved with more modern standard implementations.

πάντα ῥεῖ
- 1
- 13
- 116
- 190