newbie: delete (ifstream) file

Discussion in 'C++' started by Guest, Feb 1, 2004.

  1. Guest

    Guest Guest

    I have "unhandled exception" in line 12. Why?
    The other code works fine (if I use line 11 instead of 12).
    file allacated by new (not in stack)
    01 vector<string> Machine::getINIlines(ifstream &file)
    02 {
    03 vector<string> lines;
    04 string s;
    05 while(!file.eof())
    06 {
    07 getline(file, s);
    08 s = trim(s);
    09 if (s[0] != '#') lines.push_back(s);
    10 }
    11 // file.close();
    12 delete file;
    13 return lines;
    14 }
    Guest, Feb 1, 2004
    1. Advertisements

  2. Guest

    Guest Guest

    hmmmm!...... delete &file;
    now works!
    (there is no compiler warning/error for "delete file"!)
    Guest, Feb 1, 2004
    1. Advertisements

  3. Guest

    Phlip Guest

    Why are you deleting a file object? You should only delete things returned
    by new.

    Take out the line. If you really meant to close the file, call file.close().
    But this breaks the "symetry principle", which states that functions who
    open a file should either close it or ensure it will be closed. Callers of
    getINIlines should not be surprised their file went away.

    If you are trying to remove the file from the disk, look up 'remove()' or
    'unlink()', and then pass a file name - after the file is closed.

    Your current behavior might be due to 'file' overloads operator void*, and
    'delete' compiles thinking it can work on this. That's why the compiler
    mislead you to think that 'delete' was going to do whatever you thought it
    should do.

    Finally, there are much better ways to read INI files. These days they are
    all in XML, for example.
    Phlip, Feb 1, 2004
  4. Yes, if you newed the file, this is correct. But still don't do this:
    - Try to do the new and the delete at the same level.
    - The name getINILines does not advocate it deletes the object.
    - When deleting an object, pass a pointer, not a reference, for

    So although your code is technically correct, it is very poor style.

    Oh, BTW:

    Because it makes posts harder to read.

    Martijn Lievaart, Feb 1, 2004
  5. Guest

    Guest Guest

    hmmmm!...... delete &file;
    you are right, thanks
    Guest, Feb 1, 2004
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.