Why the next program
#include <iostream> struct C { operator int() { std::cout << "C::operator int()" << std::endl; return 0; } operator void() { std::cout << "C::operator void()" << std::endl; } }; int main() { C c; (int)c; (void)c; // this does run the function: // c.operator void(); }
bring it out
C::operator int()
instead of this?
C::operator int() C::operator void()
Live demo at coliru.
The immediate answer, as always, is because the standard says so.
C ++ 11 Standard, Β§ 12.3.2
The conversion function is never used to convert a (possibly cv-qualified) object for (possibly cv-qualified) the same type of object (or a reference to it), to the base class (possibly cv-qualit) this type (or reference to him) or (possibly cv-qualified) void.
So why does the standard say so? What is the use of using void conversion functions in a particular case?
Additional exposure in footnote 116:
These transformations are considered standard transformations for the purpose of overload resolution (13.3.3.1, 13.3.3.1.4) and, therefore, initialization (8.5) and explicit casts (5.2.9). Converting to void does not cause any conversion function (5.2.9). Although never directly called to perform the conversion, such conversion functions can be declared and can potentially be achieved by invoking a virtual conversion in the base class.
I just used (void) to disable compiler warnings about unused variables. It seems like others are using it too.
Why use unused return values ββfor void?
If the void conversion functions were performed according to the typical rules of the conversion functions, this could allow surprises, but this is true for any conversion function with side effects and creating these surprises, it would be at the discretion of the programmer.
c ++ language-lawyer type-conversion c ++ 11
Praxeolitic
source share