Archived

This topic is now archived and is closed to further replies.

Is this safe?

This topic is 5501 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Quick question. I THINK I read somewhere that if you file a file stream (fstream, ofstream, or ifstream), and you don''t call close() on it, the destructor will call close() automatically. I forget where I read this. Is it safe to have code like this, assuming the destructor will call close?
  
int main() {
  ofstream someFile("somefile.txt");
  someFile << "some text in some file.";
  return 0;
}
  

Share this post


Link to post
Share on other sites
Never make any assumptions. Yes, it is closed automatically in the deconstructor if opened via the constructor or open method, but you should be closing it manually anyway. If you were using C's fopen, you'd be responsible for closing it yourself anyway.

EDIT: If you have to ask if it's safe or not, just assume it isn't, and you won't run into too much trouble

[edited by - Zipster on November 18, 2002 2:13:53 AM]

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
quote:
Original post by Zipster
If you have to ask if it''s safe or not, just assume it isn''t

Or even better: Check the manual

Share this post


Link to post
Share on other sites
quote:
Original post by Zipster
If you have to ask if it''s safe or not, just assume it isn''t
Why? If he asks it, then he''ll know the truth and he doesn''t have to assume anything.

Share this post


Link to post
Share on other sites
Yeah, it is safe to assume it''ll close on its own. Though it isn''t exactly the best practice to do so.

Try to clean up things yourself when possible. You never know when you''ll be working on a bit of code that won''t clean up on its own and could potentially munch up ressources and memory by not deallocating them after the program ends. It''s a good idea to make it a habit to do this sort of stuff yourself.

Share this post


Link to post
Share on other sites
quote:
Original post by RuneLancer
Yeah, it is safe to assume it''ll close on its own. Though it isn''t exactly the best practice to do so.

Why not? Ever hear of RAII?
quote:

It''s a good idea to make it a habit to do this sort of stuff yourself.

It''s a better idea to understand the facilities you use and make informed decisions rather than write s/w based on superstitious practice.

Share this post


Link to post
Share on other sites
I''m not sure why everyone keeps saying "close it yourself." It''s perfectly fine to let the destructor do the closing! That''s why it''s there! Manually closing is for when you may want to open and close several times, etc. It''s perfectly safe to assume it will close because that''s what it''s defined to do.

Share this post


Link to post
Share on other sites
quote:
Original post by RuneLancer
Yeah, it is safe to assume it''ll close on its own. Though it isn''t exactly the best practice to do so.

Try to clean up things yourself when possible. You never know when you''ll be working on a bit of code that won''t clean up on its own and could potentially munch up ressources and memory by not deallocating them after the program ends. It''s a good idea to make it a habit to do this sort of stuff yourself.


No it isn''t, good programming habits dictates never to assume anything. What might be true on some architecture might not be on some other architecture. Unless you have a good garbage collector which C/C++ is pretty much lacking...




[Cyberdrek | the last true sorcerer | Spirit Mage - mutedfaith.com]

Share this post


Link to post
Share on other sites
quote:
Original post by Cyberdrek
What might be true on some architecture might not be on some other architecture. Unless you have a good garbage collector which C/C++ is pretty much lacking...

C++ has garbage collectors, even portable ones, just not Standardised ones. However, the question of whether GC is "lacking" is a more complex one.

Share this post


Link to post
Share on other sites
Obviously you close it yourself its just good practice. What comes next if you don''t close it yourself? Do you assume that you don''t have to free up memory cause there ''could be'' a util that does it for you (there isn''t one by the way no matter what sabreman says).

Always cleanup after yourself and never make any assumptions without knowing for sure if they are true. Oh and don''t bother listening to people like Sabreman who always argue''s against the grain (flame me if you must but its true from what i have seen).

Share this post


Link to post
Share on other sites
quote:
Original post by jonbell
Obviously you close it yourself its just good practice.

Why is it good practice?
quote:

What comes next if you don''t close it yourself? Do you assume that you don''t have to free up memory cause there ''could be'' a util that does it for you

You don''t *assume* anything, you read the manual, which will clearly tell you that ofstream''s dtor closes the file. You don''t write programs based on guessing how things work, it is a programmer''s job to understand what they are doing and write programs *knowing* how things work.
quote:

(there isn''t one by the way no matter what sabreman says).

Because you know everything, right? Boehm-Demers-Weiser GC.
quote:

Always cleanup after yourself and never make any assumptions without knowing for sure if they are true.

Nobody''s advocating making assumptions, they''re advocating making an informed decision.
quote:

Oh and don''t bother listening to people like Sabreman who always argue''s against the grain (flame me if you must but its true from what i have seen).

People don''t need you to tell them whether they should listen to me or not. At least credit your invisible friends with the intelligence to make their own judgements.

Share this post


Link to post
Share on other sites
Anyone does this:

  
int main()
{
std::auto_ptr<SomeStruct> p(new SomeStruct);
...
delete p.release();
}
//

// instead of

//

int main()
{
std::auto_ptr<SomeStruct> p(new SomeStruct);
...
}

So is it a good practise to free it yourself??

[edited by - DerekSaw on November 18, 2002 8:01:20 PM]

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
In a small, trivial program like this, go ahead, let the standard destructor close the files. BUT, in a *real*, useful program you should be closing the files yourself. Why have the file open during the entirity of your program when it was only used to load some graphics, sound, or data? It is good practice to pair open''s and close''s: this isn''t VB.

Besides, if you are trying to get a job, or taking a test about file handling in a programming language and you don''t close a file when you are done with it, you will be frowned upon.

Share this post


Link to post
Share on other sites
quote:
In a small, trivial program like this, go ahead, let the standard destructor close the files. BUT, in a *real*, useful program you should be closing the files yourself. Why have the file open during the entirity of your program when it was only used to load some graphics, sound, or data? It is good practice to pair open''s and close''s: this isn''t VB.



i''m not advocating not closing the file manually but surely when it goes out of scope it will get closed anyway by the destructor. so if you have function or method that loads graphics etc, when that function ends the file will get closed anyway.

Share this post


Link to post
Share on other sites
Your replies have all been very helpful. I was wondering if I needed to close the file explicitly because I have a very simple error-logging system and having to close the file explicitly would mean having to write a destructor for it.

So I've decided to let the ofstream's destructor do its job, calling close() only really helps if I need to later call open() to open a second file.

[edited by - Brobanx on November 18, 2002 8:54:38 PM]

Share this post


Link to post
Share on other sites
quote:
Original post by Anonymous Poster
In a small, trivial program like this, go ahead, let the standard destructor close the files. BUT, in a *real*, useful program you should be closing the files yourself. Why have the file open during the entirity of your program when it was only used to load some graphics, sound, or data? It is good practice to pair open's and close's: this isn't VB.

Besides, if you are trying to get a job, or taking a test about file handling in a programming language and you don't close a file when you are done with it, you will be frowned upon.

Yep, I agree that leaving the files open through out a very very long function is bad... but big program will have lot of functions supporting it. And each of the functions shouldn't be so complex.... unless you mean this (a 1000 lines function?) :

    
void SomeVeryLongFunc()
{
// alloc graphic mem

// open file when start

// load graphics

// finish loading... but file not close

...
// manipulate/modify graphics

// blah blah


// *destructor close the file*

}
// you could do it this way

void SomeVeryLongFunc()
{
// alloc graphic mem

{
// open file when start

// load graphics

// *destructor do the job*

}
...
// manipulate/modify graphics

// blah blah

}

Or maybe the loading part will be in another function.... it is better to have the loading part in another function.

[edited by - DerekSaw on November 18, 2002 9:08:06 PM]

Share this post


Link to post
Share on other sites
quote:
Original post by jonbell
Obviously you close it yourself its just good practice. What comes next if you don''t close it yourself?

It closes itself, like it''s specified as doing.

quote:
Do you assume that you don''t have to free up memory cause there ''could be'' a util that does it for you

I don''t free memory because I know that the classes I use free it for me.

quote:
(there isn''t one by the way no matter what sabreman says).

You are an idiot.

quote:
Always cleanup after yourself

Why do things manually when I can have them done automagically?

quote:
and never make any assumptions without knowing for sure if they are true.

Well duh. That''s the bloody point, isn''t it. These aren''t assumptions plucked out of thin air. We know the behaviour of the filestreams'' destructors.

quote:
Oh and don''t bother listening to people like Sabreman who always argue''s against the grain (flame me if you must but its true from what i have seen).

You are still an idiot.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
quote:
Original post by Anonymous Poster
It is good practice to pair open''s and close''s: this isn''t VB.



That''s funny. VB files always have to be closed explicitly.

Share this post


Link to post
Share on other sites
quote:
Original post by Anonymous Poster
In a small, trivial program like this, go ahead, let the standard destructor close the files. BUT, in a *real*, useful program you should be closing the files yourself.

Crap! In C++, destruction is deterministic. You know exactly when your file will be closed: when the filestream goes out of scope. What''s the problem?
quote:

Why have the file open during the entirity of your program when it was only used to load some graphics, sound, or data?

Why are people like you so stupid? Nobody''s suggesting leaving the file open for the *entirety* of your program. Learn to read and comprehend.
quote:

It is good practice to pair open''s and close''s: this isn''t VB.

Still nobody''s answered why it''s good practice. It would be nice if one of you was capable of providing some qualification for your advice. It''s a load of religious hot-air with no reasoning behind it.
quote:

Besides, if you are trying to get a job, or taking a test about file handling in a programming language and you don''t close a file when you are done with it, you will be frowned upon.

"When you are done with it" is when the filestream goes out of scope. Or are you in the habit of defining objects in an irrelevant scope?

Share this post


Link to post
Share on other sites
name calling? well, the tone is not nice.. but thats normal for sabrewulf uhm whats the name again? sabreman, sabman? ..damn do i really have to check it again?:D

well, but he''s right. the initial poster stated somewhere that if it would not close in the dtor, that he would write a wrapper class that does exactly this. so he wants to have it closed where the dtor is called. so the answer is simple: close is called in the dtor, so he does not need that wrapper..

personal note: i don''t destruct anything manually at the end of some code. that means i could forget it. c++ is there to prevent you from forgetting. define objects that behave the way you want, so that you can use them only that way. smart_ptr''s, containers, streams, ctors/dtors,scoped_braces, all just there for you to prevent typos that lead to runtime bugs.
it does not make your code really slower, and if it does, you can optimize away if you want, by removing deletion at the end and such fun..

relying on a manual destruction is unsave.. if somethign throws in the middle of your function and you catch it some way down in a primary caller function, the destruction will not happen, only dtors will get called on error..

"take a look around" - limp bizkit
www.google.com

Share this post


Link to post
Share on other sites
quote:
Original post by davepermen
relying on a manual destruction is unsave.. if somethign throws in the middle of your function and you catch it some way down in a primary caller function, the destruction will not happen, only dtors will get called on error..


simple examples:


  
void save_call() {
try {
call_function();
}catch(...) {
..handle..
}
}


you think now call_function is save?

well, we take a more detailed look:

example 1:


  
void call_function() {
int* data = new int[1024*768]; //allocating a temporary screen buffer

calling_other_function();
delete data;
}



now.. calling_other_function() is just that:


  
void calling_other_function() {
throw;
}



now, your call_function does _NOT_ delete data if calling_other_function throws (wich it does..)

save version:


  
void call_function() {
boost::scoped_ptr<int> data(new int[1024*768]);
calling_other_function();
}



or even


  
void call_function() {
std::auto_ptr<int> data(new int[1024*768]);
calling_other_function();
}


would work here..


other example:


  
void call_function() {
FILE* file = fopen("filename","r");
calling_other_function();
fclose(file);
}


unsave..



  
void call_function() {
std::fistream in("filename");
calling_other_function();
}

save..

_DON'T_ clean up manually, use your compiler.. it saves you from forgetting to do it, and it saves you from having code that does skip out of your code, wich does not know of your manual cleanup, but it knows dtors..

EDIT: those source tags look like crap, much too oversized.. anyways..:D
EDIT2: and the first edit even killed them.. wonderful..

"take a look around" - limp bizkit
www.google.com

[edited by - davepermen on November 19, 2002 10:19:07 AM]

Share this post


Link to post
Share on other sites
to quote scott meyers

''By adhering to the rule that resources should be encapsulated inside objects, you can usually avoid resource leaks in the presence of exceptions.''

its a well understood concept and it''s being used in the iostream classes.

if you understand how to use them you won''t bother with closing them manually.

if you don''t understand how to use these classes then you will close them manually with the idea that you are being safe. you don''t have to put in your extra little bits of i''m-appearing-to-be-careful code. the classes already have safety designed into them.

Share this post


Link to post
Share on other sites