In the following code, the lifetime of the temporary
bound to the static const reference in g() is wrong.
In fact, the destructor is called every time the function
is left (although the constructor is called only the
first time the function is entered, which is correct).
According to the C++ standard, the lifetime of a temporary
bound to a reference should be identical to that of the
reference -- in this case, the destructor should not
be called until final clean-up.
The compiler was invoked without any options. Running
the generated a.out reveals multiple calls to the destructor.
----- code -----
#include <iostream>
#include <ostream>
class C
{
public:
C( char id ) ;
C( C const& other ) ;
~C() ;
private:
char myId ;
} ;
void
g()
{
static C const& c = C( 'g' ) ;
std::cerr << "in g" << std::endl ;
}
int
main()
{
g() ;
g() ;
return 0 ;
}
C::C( char id )
: myId( id )
{
std::cout << "ctor: " << myId << " (@" << this << ")" << std::endl ;
}
C::C( C const& other )
: myId( other.myId )
{
std::cout << "copy: " << myId << " (@" << this << ")" << std::endl ;
}
C::~C()
{
std::cout << "dtor: " << myId << " (@" << this << ")" << std::endl ;
}
--
Summary: Wrong lifetime of temporary, calls destructor twice
Product: gcc
Version: 4.1.0
Status: UNCONFIRMED
Severity: critical
Priority: P3
Component: c++
AssignedTo: unassigned at gcc dot gnu dot org
ReportedBy: jkanze at cheuvreux dot com
GCC build triplet: sparc-sun-solaris2.8, i686-pc-linux-gnu
GCC host triplet: sparc-sun-solaris2.8, i686-pc-linux-gnu
GCC target triplet: sparc-sun-solaris2.8, i686-pc-linux-gnu
http://gcc.gnu.org/bugzilla/show_bug.cgi?id=27216