Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

c++ strings

Name: Anonymous 2007-03-21 6:35 ID:QUPvos6j

I'm not sure about how allocation and cleanup works with c++ strings. Does this leak memory?


string get_filename(char * path)
{
    string file_name = path;
    int pos = file_name.find_last_of('\\');
    if (pos!=string::npos)
    {
        file_name = file_name.substr(pos+1); // what happens to the memory here?
    }
    return file_name;
}

Name: Anonymous 2007-03-21 6:47 ID:BHEYEZtV

std::string manages its own memory automatically.  If there's no explicit heap allocation on your part, then you've got nothing to worry about.

In your particular example, you won't somehow leak the old file_name string when you reassign file_name.  The assignment operator will make sure it's properly dealt with.  (Though, if memory serves, you'd be better off with "string file_name(path);" than with "string file_name = path;").

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List