See the program below. The program should print 1 as 1 counter object still exists, but when compiled with GCC, it prints 0. Why is that? Is this a compiler bug? This only occurs when returning from a different scope. Removing the if completely fixes it on all compilers.
#include <iostream>
int counter = 0;
class Counter {
public:
Counter() {
counter++;
}
~Counter() {
counter--;
}
};
Counter test() {
if (true) { // REMOVING THIS FIXES IT
Counter c;
return c;
} else {
throw std::logic_error("Impossible!");
}
}
int main() {
Counter c = test();
std::cout << counter << std::endl; // 0 on GCC (incorrect), 1 on clang (correct)
return 0;
}