C++ management of strings allocated by a literal

后端 未结 4 1508
终归单人心
终归单人心 2020-12-10 15:44

Do I need to take care of memory allocation, scope and deletion of C++ strings allocated by a literal?

For example:

<         


        
4条回答
  •  执笔经年
    2020-12-10 16:06

    • func1() returns a pointer to a string literal. You must not delete string literals.
    • func2() (presumably, you omitted the std:: prefix) returns a std::string. It takes care of itself.
    • func3() returns a pointer to a string that's managed by a std::string object that's destroyed when the function exits. You must not touch that pointer after the function returns.
    • You would have to take care of the memory returned by this function:

      const char* func4() {
         char* s = new char[100];
         // fill char array with a string
         return s;
      }
      

    However, manual resource management is tricky. For starters, if a function returns a naked pointer, you don't know whether it points to one objects (char) or an array thereof and whether you need to delete it. You should avoid all that and just stick to std::string.

提交回复
热议问题