# Trouble-making destructor

## Recommended Posts

Calin    419
I have a destructor that operates out of nothing, right in the middle of application. It operates at the end of a function:

Update( some arguments);
Log("End of Update\n");

//Update definition
void Update(...)
{
//code removed
Log("Exiting Update function \n");

// Here is the place where the distructor gets called
}


I use a Log file to track down the errors. The Log file output:
Exiting Update function
--------WARNING: Sound object not released--------
Shuting down sound ClkChildB
--------WARNING: Sound object not released--------
Shuting down sound ClkParentB
End of Update


The warnings are printed by the distructor. Could anyone point out the cause of this behavior ?

##### Share on other sites
iMalc    2466
Post the real code, or at least post code which has been slightly stripped down, but still produces the problem.

You haven't posted you code which is logging your warning messages, either.

You do know that anything that was constructed inside a function is of course destructed when the function exits (except static vars)? Even if you have an early return statment.

##### Share on other sites
Telastyn    3777
Uh right, the destructor of an object is called when it goes out of scope.

Most likely you're passing the object by value as a parameter to Update. A new object is created at entry of the function, and is thus destructed when the function ends:
#include <iostream>struct Object{    int x;    Object(){        std::cout << "Made 1 object.\n";    ~Object(){        std::cout << x << " dies!\n";    }};void Update(Object foo){    // stuff!}int main(){    Object *bar=new Object();    bar->x=42;    Update(*bar);    delete bar;}

So what should this code do?

Made 1 object.42 dies!42 dies!

The copy's destructor is called at the end of Update(), thus creating the perhaps unexpected duplication of death messages.

##### Share on other sites
Calin    419
Yeah, I was passing an object by value, thank you both.