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 *缓冲区,那么您可能会得到一些意外的行为。 strike>
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,那么最好使用
无论如何,当然您不应该删除返回的指针。
std :: string.c_str()返回一个以nul结尾的字符串的指针。实际的字符数组仍归std :: string对象所有,并且只要以下条件有效:
由字符串对象本身来分配和释放它返回给您的nul终止的字符数组。
您始终可以将以nul终止的字符串用作未以nul终止的字符串。毕竟,NTS只是非NTS,结尾处有一个额外的零。只要按照函数期望正确地终止了字符串,它就永远不会出现"多余"的nul。 :)