4

I'm currently studying C++ standard and came to this insane example:

#include <iostream>

int i = 0;

class A {
public:
    operator void() {
        std::cout << ++i << std::endl;
    }
};

int main() { 
    A a, b;
    A c = (a, b);
    static_cast<void>(a);
    (void) a;
}

Despite the fact that operator void() has side effects, it is never called (at least nothing is printed to stdout). However operator void() is not disallowed, the only way I found to trigger it is to use volatiles:

5.2.9 Static cast [expr.static.cast]

[...] Any expression can be explicitly converted to type cv void, in which case it becomes a discarded-value expression (Clause 5).

5 Expressions [expr]

[...] The lvalue-to-rvalue conversion (4.1) is applied if and only if the expression is a glvalue of volatile-qualified type and it is one of the following: [...]

As of N3797 draft

I have tried to add volatile to my code, but nothing printed.

Is there way to trigger operator void() or it is dead code? Of course question is speculative, no practical use behind it.

I have checked my example with G++ 4.9 and CLang++ 3.3

myaut
  • 11,174
  • 2
  • 30
  • 62

0 Answers0