The following piece of code compiles and runs without errors and with the expected output:
#include <string>
#include <iostream>
using namespace std;
string getString()
{
char s[] = "Hello world!";
return s;
}
int main()
{
cout << getString() << endl;
}
My question is, will this always work? Ordinarily if you return a C-string that was declared locally you can run into some undefined behavior, but in this case is that still a problem since it is run through the string constructor and (presumably) copied into dynamic memory?
std::stringadded to standard library - it can be used as an embedded type likeintanddouble, so yes it is fine to returnstd::stringby value.const char* s="Hello World"you can safely return it from your function, since s is a pointer to an object with static storage duration. This is whystd::except::what()ortype_info::name()return a c-string