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 12:07 ID:TrNDlqTT

>>3

Close, but not quite.  "string file_name(path)" is a constructor call.  However, "string file_name = path;" is a call to the overloaded assignment operator.

I think this assignment operator is defined as =(string, string), so the C++ compiler helpfully rewrites "string file_name = path;" to "string file_name = string(path);".  This is one more object copy than the constructor call, so a tiny bit slower.  But AFAIK that's not the point, the main problem is there are more places for exceptions to be thrown.

I'm only intermediate, so C++ experts will find mistakes in the above.  Still, it should be the gist of it.

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