C ++, are fstream objects passed to functions as reference, const?

I know that generally, data references should be isolated as a constant within a function so that the function cannot change it, is the same true for fstream objects that are used only for input?

Such as the...

void doFoo(fstream &fileName)
{
  fileName.open("data.txt", ios::in);
} 

      

IF it makes sense, should he follow the same logic of most others?

Such as the...

void doFoo(const fstream &fileName)
{
  fileName.open("data.txt", ios::in);
} 

      

also interested in output streams as well

I'm just wondering if this matters, and if so, why?

thank!

+3


source to share


2 answers


The file constant is not converted to a constant attribute of the object used to access the file. Even for a simple file read, you have to change internal buffers, current read position, etc. The same goes for output, so basically const stream is not useful.



BTW: If you want to clarify that a function only reads from a stream, pass it std::istream&

. First, the "i" in istream

makes sure you are not writing to it. Second, the missing "f" from fstream

is usable with string streams or streams such as cin.

+6


source


If you pass an object (like an instance fstream

) as a constant reference, you can only call const

member functions on it, like this:

// In some class declaration
void aConstMember(int a) const;

      



This is because such functions do not change the state of the object, so the object can be const

. Non-const member functions can modify member variables, so the object will no longer be const. Now if you look at the reference manual for fstream

, you will see that the member function is open()

not constant. Therefore, the second code example will not compile.

In general: pass class type arguments as const &

if they will not be changed in the function. Opening a stream is definitely a modification. So just pass it by non-const reference.

+1


source







All Articles