Why operator void*() conversion function added to the C++ stream classes?

前端 未结 2 1552
星月不相逢
星月不相逢 2021-02-19 13:57

There is a conversion function operator void*() const in C++ stream classes. so that all stream objects can be implicitly converted to void*<

2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-19 14:18

    This is a flaw in the C++ standard library.

    This was a flaw in older versions (1998 and 2003) of the C++ standard library. This flaw no longer exists in 2011 and later versions of the standard. A new feature, the ability to mark conversion operators as explicit, was added to the language to make a conversion operator to bool safe.

    The developers of the original version of the C++ standard explicitly chose to use a conversion to void* rather than a conversion to bool because a non-explicit conversion to bool was quite unsafe in a number of ways. In comparison, while operator void*() was rather obviously kludgy, it worked, at least so long as you didn't cast that pointer to something else or try to delete it. (An alternative, operator!, was arguably safer than either of those conversion operators, but that would have required the non-intuitive and abstruse while (!!stream) {...}. )

    The concept of the "safe bool" idiom was developed after the original 1998/1999 version of the standard was released. Whether it was developed prior to 2003 is a bit irrelevant; the 2003 version of the standard was intended to be a bug fix to that original standard. That operator void*() let delete std::cin compile wasn't deemed a bug so much as a "don't do that then" kind of problem.

    The development of the "safe bool" idiom showed that alternatives did exist that made operator bool() safe, but if you look at any of the implementations, they are all massively convoluted and massively kludgy. The C++11 solution was amazingly simple: Allow conversion operators to be qualified with the explicit keyword. The C++11 solution removed the void* conversion operator and added an explicit bool conversion operator. This made the "safe bool" idiom obsolete, at least so long as you are using a compiler that is C++11 (or later) compliant.

提交回复
热议问题