问题
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?
In short:
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.
回答1:
No you don't need to deallocate the ptr
pointer.
ptr
points to a non modifyable string located somewhere to an internal location(actually this is implementation detail of the compilers).
Reference:
C++ documentation:
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.
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 guaranteed to remain unchanged until the next call to a non-constant member function of the string object.
回答2:
No need, the dtor of the string class will handle the destruction of the string so when 'hello' goes out of scope it is freed.
回答3:
std::string handles this pointer so don't release it. Moreover, there are two limitations on using this pointer:
1. Don't modify string that is pointed by this pointer, it is read-only.
2. This pointer may become invalid after calling other std::string methods.
回答4:
Not only you don't need to free the pointer but you in fact should not. Otherwise the destructor of std::string
will attempt to free it again which may result in various errors depending on the platform.
回答5:
The std::string
class is responsible for freeing the memory allocated to contain the characters of the string when an object of the class is destructed. So if you do
delete[] Ptr;
before or after hello
object is destructed (leaves the C++ {}
scope it was created in), your program will run into a problem of trying to free a memory block that is already freed.
来源:https://stackoverflow.com/questions/7460753/does-a-pointer-returned-by-stdstring-c-str-or-stdstring-data-have-to-be