Why isn't delete needed for the c_str() member function of the string class?

The c_str() function returns a pointer to a c style string of the string object but how does it work such that delete isn't needed?
Because std::string::c_str() doesn't transfer ownership with the pointer. The pointer belongs to the object that returned it and it's its responsibility to free it.
err so if let's say the string object goes out of scope/destroyed then my pointer that I used to point to the c style string after calling c_str() would become a dangling pointer?
Yes.
1
2
3
4
5
6
const char *p;
{
    std::string s="hello";
    p=s.c_str();
}
//p is invalid 
ok thanks for the explanation, then if I explicitly called delete on my pointer which points to the c style string, then the string object would be left in an inconsistent state? or is there a mechanism to prevent this from happening?
I don't think you would be able to, since it is a pointer to a const char.
ok thanks for clearing it all up :)
Topic archived. No new replies allowed.