tags:

views:

285

answers:

5

Hi

Is this correct, it works OK

string str("in.dat");
ifstream fin(str.c_str(), ios::binary | ios::ate );
.
.
.
//Do I need to clear the string before assigning new name???
str = "out.dat";
ofstream fout(str.c_str(), ios::binary); //seems to work

Regards

+2  A: 

What you did is correct. The = operator will overwrite string contents, it's normal scenario of reusing string variable. It will even probably not realloc any buffer, but reuse existing instead.

+2  A: 

It's correct to do so. Assignment, in any language, means the object loses its old value and acquires a new one.

Thank you much appreciated
+1  A: 

No, just assigning a new value is fine. It's the string class' responsibility to make sure that assignment works, that it doesn't introduce leaks.

unwind
Thanks for the help
+4  A: 

What everyone else has said is true. However, in the code you posted you could just as well have said:

ifstream fin( "in.dat", ios::binary | ios::ate );
ofstream fout( "out.dat", ios::binary );
anon
I might add it's to be preferred. From a code-reading point of view.
xtofl
Depends if he uses the name for something else (like an error message) in the code he didn't post. I just wanted to make surwe he knew that he didn't always have to use s.c_str().
anon
A: 

Though it's valid C++, it's not very nice C++.

The reader of your code needs to remember that the str variable is mutable, and serves a different purpose throughout your code file. When code is inserted between the second assignment of str and it's use as a filename, the reader may find it hard to find out what's in the variable.

It's always better to give your variables a sensible name; it then almost always becomes constant.

const char* inputpath("in.dat");
ifstream inputstream( inputpath, ... );

const char* outputpath("out.dat");
... lots of code
ofstream outputstream( outputpath, ... );
xtofl
The file stream constructors take a const char * as their first parameter, not a std:;string.
anon
Thanks, Neil. Corrected that.
xtofl