Implicit cast to bool of basic_istream/ifstream/ofstream doesn't work in Visual Studio 2013

后端 未结 3 1174
小鲜肉
小鲜肉 2021-01-14 18:26

The code below compiles in VS 2012 but not in VS 2013

std::ofstream stm;
if(stm != NULL)
{
}

In VS 2013 you get this compilation error:

3条回答
  •  不要未来只要你来
    2021-01-14 18:59

    C++11 requires some boolean conversions to be explicit that used to be implicit. This is noted in Appendix C about compatibility with C++03:

    C.2.15 Clause 27: Input/output library [diff.cpp03.input.output]

    27.7.2.1.3, 27.7.3.4, 27.5.5.4

    Change: Specify use of explicit in existing boolean conversion operators

    Rationale: Clarify intentions, avoid workarounds.

    Effect on original feature: Valid C++ 2003 code that relies on implicit boolean conversions will fail to compile with this International Standard. Such conversions occur in the following conditions:

    • passing a value to a function that takes an argument of type bool;
    • using operator== to compare to false or true;
    • returning a value from a function with a return type of bool;
    • initializing members of type bool via aggregate initialization;
    • initializing a const bool& which would bind to a temporary.

提交回复
热议问题