Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid "(void)a" cast causing side-effects?

Tags:

c++

gcc

void

I have this code and GCC prints "what!?". How can I avoid that, so that the void cast simply has the C meaning "Ignore the lonely 'a;'"?

#include <iostream>

struct A {
  template<typename T>
  operator T() { 
    std::cout << "what!?";
  }
};

int main() {
  A a;
  (void)a;
}
like image 250
Johannes Schaub - litb Avatar asked Aug 03 '12 10:08

Johannes Schaub - litb


2 Answers

As you've observed, this is a bug in gcc. The standard reads:

c++11

12.3.2 Conversion functions [class.conv.fct]

(1) A conversion function is never used to convert a (possibly cv-qualified) object to [...] (possibly cv-qualified) void.
116) A conversion to void does not invoke any conversion function (5.2.9).

5.2.9 Static cast [expr.static.cast]

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

As a workaround, you could write:

a, void();

It's impossible to overload operator,(void) so there is zero chance of this invoking user-defined behaviour from a conformant implementation.

like image 181
ecatmur Avatar answered Sep 23 '22 17:09

ecatmur


Adding an

operator void() {}

takes care of it.

like image 42
Jon Avatar answered Sep 22 '22 17:09

Jon