Based on the idea of this entry Is it a good idea to return “ const char * ” from a function?
I thought to extend this with another question I have.
Consider the following code:
#include <string>
#include <cstdio>
const char * GetSomeString() 
{ 
  std::string somestlstring;
  somestlstring = "Hello World!";
  return somestlstring.c_str(); 
}
int main()
{
  const char * tmp = GetSomeString();
  printf("%s\n", tmp);  
  return 0;
}
If I build it with
g++ source.cpp -o executable
and execute that, I get strange symbols displayed. This is because somestlstring is destroyed through the callstack and the pointer you keep after returning became invalid.
My question is: how should I design a method or function that does not have such behaviour without actually declaring additional global variables or potential member functions?
 
     
     
     
     
    