Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`ofstream` compared to 0

I'm upgrading existing old code to use VS 2019*, in the code I have the following function that fails on the return line:

int foo(const char *fn) const
{
    ofstream out(fn,ios::binary);
    if (out)
    {
        //...
    }
    return out!=0;
}

The error I get is:

Error C2678 binary '!=': no operator found which takes a left-hand operand of type 'std::ofstream' (or there is no acceptable conversion)

What was the original poet's intention, and what is the best way to fix the issue?

*This code compiles successfully on VS 2010.

like image 384
SIMEL Avatar asked Jan 09 '20 10:01

SIMEL


2 Answers

I suppose with the upgrading, you're switching to C++11 mode.

Before C++11, std::basic_ios (the base class of std::basic_ofstream) could convert to void* implicitly.

Returns a null pointer if fail() returns true, otherwise returns a non-null pointer.

Then out!=0 is checking whether the stream has no errors and is ready for further I/O operations.

Since C++11, there's only one conversion operator which could convert std::basic_ios to bool. Note that the operator is marked as explicit, so the implicit conversion isn't allowed for out!=0.

You can change the code to !!out (invoking operator!), or !out.fail(), or static_cast<bool>(out) (explicit conversion via operator bool).

like image 67
songyuanyao Avatar answered Nov 19 '22 01:11

songyuanyao


There are two operators in the class std::basic_ios that can be applied in such a situation. They are

explicit operator bool() const; 
bool operator!() const; 

So you can for example either write

return bool( out );

or

return !!out;

or

return !out != true;
like image 1
Vlad from Moscow Avatar answered Nov 19 '22 01:11

Vlad from Moscow