g++ bug with optimization, destructor not call, invalid code

Renaud Lepere Renaud.Lepere@imag.fr
Wed Apr 26 02:53:00 GMT 2000


Hello,

The following program doesn't compile well, with 
gcc version 2.95.1 19990816 (release) when optimization options are
used -O2. (same problem on i686 and Sparc).
The code generated seems to be incorrect, with -O

#include <iostream>

using namespace std;

struct add
{
  add() { cout << "."; };
  ~add() { cout << "~"; };
  int operator() (int res, int i, int j) {
    if (i < j) 
      return add()(res + i, i + 1, j);         /* the problem is here */ 
    else
      return res;
  };
};
  
int main()
{
  int res;
  {
    res = add()(0, 0, 5);
  };
  cout << endl << res << endl;
  return 0;
}

Here is the output of the program without -O
......~~~~~~
10
and with optimization -O
......~
10
The destructor is called only once.
    
Here is a part of the code "corresponding" to the begining of the line
res = add()(0,0,5). (with optimization -0)

.LEHB481:
	xorl %esi,%esi
	xorl %ebx,%ebx
	movl $5,%edi
.L483:
	cmpl %edi,%ebx
	jge .L484
	addl $-8,%esp
	pushl $.LC0
	pushl $cout
	call __ls__7ostreamPCc
	addl $16,%esp
	addl %ebx,%esi
	incl %ebx
	jmp .L483

Apparently the compiler does lot's of things, since it suppress
recursivity. The problem here is that a destructor to the temporary
should be called. In fact, i think that sadly recursivity can't be 
avoided in this case.

  Renaud.





More information about the Gcc-bugs mailing list