This is the mail archive of the gcc-bugs@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

Re: destructor of referenced object doesn't work


Takashi Sasaki wrote:
> 
>   version       gcc version 2.95.2 19991024 (release)
>   OS            DEC Alpha OSF1  (Compaq True64)
> 
>   In the following code, destructor of TestClass doesn't called.
>   When the reference 'r' is out of scope, the destructor must
>   be called.
> 
> ------------------------------------------------------
> class TestClass
> {
> public:
>   TestClass(void){cout <<"constructed." << endl;}
>   ~TestClass(){cout << "destructed." << endl;}
> };
> 
> int main (void)
> {
>   for(int i=0; i<10 ; i++) {
>     TestClass& r = *new TestClass ;
>   }
> }
> -------------------------------------------------------

No, the compiler is correct not to destroy it. A reference only destroys
its referent when it dies if the referent is a temporary; in this case
it is not. The only temporary involved here is the pointer returned by
new; the object it points to is constructed on the free store and is not
a temporary. There is no delete to match the new, so the object is never
destroyed.

--
Ross Smith <ross.s@ihug.co.nz> The Internet Group, Auckland, New Zealand
========================================================================
    "Be careful about using the following code -- I've only proven
    that it works, I haven't tested it."           -- Donald Knuth

Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]