I just stumbled over this piece of code:
std::string export_str = "/path/to/file";
std::ofstream export(export_str.c_str());
if (export < 0) {
std::cout << "Unable to export" << std::endl;
return -1;
}
This compiles and runs fine with GCC 4.9.3 but on GCC 6.1.1 this error comes up:
error: no match for ‘operator<’ (operand types are ‘std::ofstream {aka std::basic_ofstream<char>}’ and ‘int’)
if (export < 0) {
~~~~~~~~~~~^~~
I tried GCC 6 with:
-std=c++98
(does compile)
-std=c++03
(does compile)
-std=c++11
(does not compile)
Edit:
However, in GCC 4 it still compiles with -std=c++11
. This specific fact is also explained in the answer below. :)
So I guess there was a change in the standard regarding this.
After some research I changed the code to:
std::string export_str = "/path/to/file";
std::ofstream export(export_str.c_str());
if (export.fail()) { // <-- related change
std::cout << "Unable to export" << std::endl;
return -1;
}
This compiles and runs fine but I did not find a good explanation for this change, probably due to not coming up with a good search term combination.
So my question is not "How to check validity of ofstream". There are quite some more or less satisfying answers already ("more or less" because the issue seems to be a bit complicated).
Here or here or here.
My question is for an explanation for the change made between GCC 4 and GCC 6 regarding compiling things like (export < 0)
in the above code.
Thank you for any pointers.