Best way to open files

D

Dave Mill

I have implemented a class which performs operations on some file
throughout different methods in the class.

I did this by making the ifstream a private class member and opening the
file in the constructor,

however someone told me this was bad practice to have the stream as a
class attribute.

what is the best way to do it?
 
D

Donovan Rebbechi

I have implemented a class which performs operations on some file
throughout different methods in the class.

I did this by making the ifstream a private class member and opening the
file in the constructor,

however someone told me this was bad practice to have the stream as a
class attribute.

Not sure why -- but here are two issues:
(1) you can't copy or assign. Not necessarily a problem, but depends on how
you're using it. You've got to think about whether the object you're modelling
can truly be "copied".
(2) stack space: sizeof(ifstream) is 280 on my compiler, so it's very waste
to create streams that you're not using

About (2): you can use pointer and dynamically allocate when you use it.
About (1): use a shared pointer if you want a working copy constructor and
assignment.

Cheers,
 

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. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,202
Messages
2,571,057
Members
47,663
Latest member
josh5959

Latest Threads

Top