James Kanze
2009-12-07 15:16:30 UTC
Is this a known bug, and does anyone know a work-around? If a
program returns a local variable defined in a loop, the variable
isn't correctly destructed when the return statement isn't
executed.
----- CompilerError.cpp -----
#include <iostream>
#include <stdlib.h>
class Tracker
{
public:
static int instance_count ;
#define TRACK(f) std::cout << "Tracker::" #f << "(), this = " << this
<< std::endl;
Tracker() { TRACK(ctor); ++ instance_count ;}
Tracker(Tracker const& ) { TRACK(copy); ++ instance_count ;}
~Tracker() { TRACK(dtor); -- instance_count; }
Tracker const& operator=(Tracker const& ) { TRACK(asgn); return
*this; }
#undef TRACK
};
int Tracker::instance_count = 0;
Tracker f()
{
for ( int i = 0; i < 2; ++ i )
{
std::cout << i << ": start" << std::endl;
Tracker t;
if ( i != 0 )
{
std::cout << i << ": returning" << std::endl;
return t;
}
std::cout << i << ": end" << std::endl;
}
std::cerr << "I don't believe it" << std::endl;
abort();
}
void g()
{
Tracker t(f());
std::cout << "After f()" << std::endl;
}
int
main()
{
g();
std::cout << Tracker::instance_count << " remaining Trackers" <<
std::endl;
return 0;
}
----- CompilerError.cpp -----
The bug only occurs when optimization is activated (/O2). As a
work around, it's sufficient to move the variable outside of the
loop, and use assignment in the loop.
--
James Kanze
program returns a local variable defined in a loop, the variable
isn't correctly destructed when the return statement isn't
executed.
----- CompilerError.cpp -----
#include <iostream>
#include <stdlib.h>
class Tracker
{
public:
static int instance_count ;
#define TRACK(f) std::cout << "Tracker::" #f << "(), this = " << this
<< std::endl;
Tracker() { TRACK(ctor); ++ instance_count ;}
Tracker(Tracker const& ) { TRACK(copy); ++ instance_count ;}
~Tracker() { TRACK(dtor); -- instance_count; }
Tracker const& operator=(Tracker const& ) { TRACK(asgn); return
*this; }
#undef TRACK
};
int Tracker::instance_count = 0;
Tracker f()
{
for ( int i = 0; i < 2; ++ i )
{
std::cout << i << ": start" << std::endl;
Tracker t;
if ( i != 0 )
{
std::cout << i << ": returning" << std::endl;
return t;
}
std::cout << i << ": end" << std::endl;
}
std::cerr << "I don't believe it" << std::endl;
abort();
}
void g()
{
Tracker t(f());
std::cout << "After f()" << std::endl;
}
int
main()
{
g();
std::cout << Tracker::instance_count << " remaining Trackers" <<
std::endl;
return 0;
}
----- CompilerError.cpp -----
The bug only occurs when optimization is activated (/O2). As a
work around, it's sufficient to move the variable outside of the
loop, and use assignment in the loop.
--
James Kanze