c++ - Design a method or function which returns a valid string -


based on idea of entry is idea return “ const char * ” function?

i thought extend question have.

consider 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 build with

g++ source.cpp -o executable 

and execute that, strange symbols displayed. because somestlstring destroyed through callstack , pointer keep after returning became invalid.

my question is: how should design method or function not have such behaviour without declaring additional global variables or potential member functions?

you should drop whole c mindset , start writing c++:

#include <string> #include <iostream>  std::string getsomestring()  {    std::string somestlstring;   somestlstring = "hello world!";    return somestlstring;  }  int main() {   std::string tmp = getsomestring();    std::cout << tmp << std::endl;    return 0; } 

Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -