Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destructor Called Twice While No Copy Constructor or Assignment Operator Gets Callled

Tags:

c++

destructor

I have a class:

class A
{
public:
    A()
    {
        std::cout << "Constructor called" << std::endl;
    }

    ~A()
    {
        std::cout << "Destructor called" << std::endl;
    }

    A(const A& another)
    {
        std::cout << "Copy constructor called" << std::endl;
    }

    A& operator=(const A& another)
    {
        std::cout << "Assignment operator= called" << std::endl;
    }
};

In my very complicated project, I got the following output after I started my app:

Constructor called

but when I Ctrl+C to terminate my app:

Destructor called
Destructor called

And in the whole process, no copy constructor or assignment operator got called.

My class A has dynamic memory allocation, and I have to free it in the destructor, but the destructor is called twice somehow, which is very bad.

I don't know what could cause this problem.

I googled and searched a lot. A lot of questions about "destructor called twice" is because of the the implicit calling of the copy constructor (assignment operator).

Thanks.

Peter

like image 853
Peter Lee Avatar asked May 31 '11 18:05

Peter Lee


1 Answers

If you are somehow calling the destructor twice, maybe you have two objects that think they own it through a pointer.

If you really do have two objects that think they own this one, consider using a reference counted pointer such as Boost::shared_ptr or tr1::shared_ptr to contain it. That way you don't have to worry about who calls the destructor finally.

Aside from the debugger, you could try Valgrind (memcheck) to find where your program deletes an already freed object. It probably won't give more detail than the debugger in this case, but you ought to learn to use Valgrind (memcheck) sooner or later.

Another paranoid strategy is to make sure to set any internal pointers to NULL after you delete them.

like image 99
Erik Olson Avatar answered Oct 05 '22 08:10

Erik Olson