是否必须释放由std :: string.c_str()或std :: string.data()返回的指针? [英] Does a pointer returned by std::string.c_str() or std::string.data() have to be freed?

查看:95
本文介绍了是否必须释放由std :: string.c_str()或std :: string.data()返回的指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,当您调用 c_str()/ data()时, std :: string 将为其内容创建一个ident数组副本.方法(有/无终止NUL-char,在这里无关紧要).无论如何,该对象是否还需要释放此数组?还是必须这样做?

As far as i know, std::string creates a ident array-copy of its content when you call the c_str()/data() methods (with/out terminating NUL-char, does not matter here). Anyway, does the object also take care of freeing this array or do I have to?

简而言之:

std::string hello("content");

const char* Ptr = hello.c_str();

// use it....

delete[] Ptr;   //// really ???

在内存分配方面,我只想保持安全.

I just want to be on the safe side when it comes to memory allocation.

推荐答案

不,您不需要取消分配 ptr 指针.

No you don't need to deallocate the ptr pointer.

ptr 指向一个位于内部位置 (实际上是编译器的实现细节)上的不可修改的字符串.

ptr points to a non modifyable string located somewhere to an internal location(actually this is implementation detail of the compilers).

参考:

C ++文档 :

C++ documentation:

const char* c_str ( ) const;

获取等效的C字符串

生成一个以空终止的字符序列(c字符串),其内容与字符串对象相同,并将其作为指向字符数组的指针返回.

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.

返回的数组指向内部位置,该位置具有此字符序列所需的存储空间及其终止的空字符,但不应在程序中修改此数组中的值,只能保证保留该值直到下一次调用该字符串对象的非恒定成员函数之前,该值保持不变.

这篇关于是否必须释放由std :: string.c_str()或std :: string.data()返回的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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