c++stringtemporary-objects

Why I don’t have to free string from c_str function of std::string?


Why I don’t have to free string from c_str function of std::string? How the function generate const char* and how it be destroyed?


Solution

  • The const char* return from c_str() is managed by the std::string itself, and is destroyed when the std::string goes out of scope. In this regard, one must be careful they don't attempt to use the pointer returned from c_str() after the std::string is destroyed:

    const char* getName()
    {
        std::string name = "Joe";
        return name.c_str();
    }
    

    The above is wrong because when name is destructed as getName returns, the pointer will become invalid.