关于内存管理:c ++ char数组是否超出范围?

c++ char array out of scope or not?

我有一个方法需要const char指针作为输入(不以null终止)。 这是我在项目中使用的库(TinyXML)的要求。 我从string.c_str()方法调用中获得了该方法的输入。

是否需要删除此char指针? 调用完成后,字符串立即超出范围; 所以该字符串应使用其析构函数调用将其删除,对吗?


不要删除从std :: string :: c_str获得的内存。字符串是造成这种情况的原因(而且完全有可能给您提供了指向其内部缓冲区的指针,因此,如果删除了它,那将是一件坏事(tm))。


string.c_str()返回的char数组被nul终止。如果tinyXML的函数采用一个非nul终止的char *缓冲区,那么您可能会得到一些意外的行为。

const char* c_str ( ) const;

Get C string equivalent

Generates a null-terminated sequence
of characters (c-string) with the same
content as the string object and
returns it as a pointer to an array of
characters.

A terminating null character is
automatically appended.

不,它不需要被释放。 String的析构函数为您完成了此任务。

The returned array points to an
internal location with the required
storage space for this sequence of
characters plus its terminating
null-character, but the values in this
array should not be modified in the
program and are only granted to remain
unchanged until the next call to a
non-constant member function of the
string object.

来源:http://www.cplusplus.com/reference/string/string/c_str/


另一个注意事项,
如果不需要使char指针终止为null,那么最好使用str.data()而不是str.c_str()。不同之处在于.data()不会使您得到的内容将被终止为null。如果您的字符串恰好占据了string分配的内部缓冲区的整个长度,这将很有用。在这种情况下,调用.c_str()将强制string将日期重新分配给新的更大的缓冲区,该缓冲区包含足够的空间以最后添加'\0'

无论如何,当然您不应该删除返回的指针。 string会解决这个问题。


std :: string.c_str()返回一个以nul结尾的字符串的指针。实际的字符数组仍归std :: string对象所有,并且只要以下条件有效:

  • std :: string对象有效,并且
  • 没有调用std :: string对象上的非const成员函数(即,修改字符串会使之前指向的任何C风格字符串无效)。
  • 由字符串对象本身来分配和释放它返回给您的nul终止的字符数组。

    您始终可以将以nul终止的字符串用作未以nul终止的字符串。毕竟,NTS只是非NTS,结尾处有一个额外的零。只要按照函数期望正确地终止了字符串,它就永远不会出现"多余"的nul。 :)