c ++字符串分配 [英] c++ string allocation

查看:64
本文介绍了c ++字符串分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要处理关于c ++string对象的内存分配,范围和删除吗?

do I need to take care of memory allocation, scope and deletion about c++ "string" object?

例如:

#include <string>

const char* func1() {
   const char* s = "this is a literal string";
   return s;
}

string func2() {
   std::string s = "this is a literal string";
   return s;
}

const char* func3() {
   std::string s = "this is a literal string";
   return s.c_str();
}

void func() {
   const char*  s1 = func1();
   std::string s2 = func2();
   const char*  s3 = func3();

   delete s1; //?
   delete s3; //?
}

func2:我不需要'delete's2。
func3:我需要'删除s3'吗?

func2: I don't need to 'delete' s2. func3: do I need to 'delete s3' ?

btw,func1是否正确?在离开func1范围后字符存储器内容是否仍然可用?如果是,当我不再需要它时,是否应该删除它?

btw, is func1 correct? Is character memory content still available after it leaving func1 scope? If yes, should I delete it when I do not need it any more?

推荐答案


  • func1()返回一个指向字符串文字的指针。您不能删除字符串文字。

  • func2()(假设您省略了 std :: 前缀)返回 std :: string 。它照顾自己。

  • func3()返回指向由 std :: string 对象,当函数退出时被销毁。函数返回后不能触摸该指针。

  • 您必须处理此函数返回的内存:

    • 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;
      }
      


    • 管理是棘手的。对于初学者,如果一个函数返回一个裸指针,你不知道它是否指向一个对象( char )或其数组,以及是否需要删除它。你应该避免这一切,只需坚持 std :: string

      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.

      这篇关于c ++字符串分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆