Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destructor called twice

Tags:

c++

vector

EDIT: Turns out that this happens whether or not I use a vector. It has to do with objects local to the function having automatic destruction, despite my attempted explicit call to the destructor.

I'm trying to figure out why my object is apparently deleted twice. I was experimenting with the std::vector class and wanted to see how deletion of a object was handled. Can anyone enlighten me as to what is going on in this situation?

Code:

#include<iostream>
#include<vector>
#include"DummyClass.h"
using namespace std;

void main(void){
    //Make vector
    vector<DummyClass> objVect1;

    //Make objects to contain
    DummyClass test;

    //pass by value
    objVect1.push_back(test);   //makes a pass-by-value copy, I think?


    //Delete the objects stored in the array 
    objVect1.clear();   // call dtor (vector's copy)

    test.~DummyClass(); //call dtor on test
}                       //dtor called on test again?

console output:

0033F9DB was constructed
0062C200 was destructed
0033F9DB was destructed
0033F9DB was destructed

The last object is destructed two times. I am trying to figure out what is going on. It seems there was no constructor called for the copy-by-value argument passed into the vector. Can anyone help me figure this out? Thanks!

The class header is:

#pragma once
#include<iostream>
class DummyClass
{
public:
    DummyClass();
    ~DummyClass();
};

The class cpp is:

DummyClass::DummyClass()
{    
    std::cout << this << " was constructed" << std::endl;
}

DummyClass::~DummyClass()
{
    std::cout << this << " was destructed"<< std::endl;
}
like image 797
Enigma22134 Avatar asked Aug 02 '26 20:08

Enigma22134


2 Answers

The last object is deconstructed two times.

Once when you explicitly destruct it, and then once again when the function ends and all variables local to the function auto-destruct. This is undefined behavior.

You should almost never call a destructor yourself.

like image 99
user2357112 supports Monica Avatar answered Aug 05 '26 10:08

user2357112 supports Monica


DummyClass test;

This object is in the main function and will go out of scope when main returns. (1 destructor called)

objVect1.push_back(test);

A copy of the DummyClass is added to the std::vector.

objVect1.clear();

The copy is destroyed when clear is called. (1 destructor called)

test.~DummyClass()

You should not be explicitly calling this destructor, it happens automatically when the object goes out of scope (i.e., when the main function returns). (1 destructor called)

The destructor function was called 3 times, as shown above, for 2 object instances. The explicit destructor call should be removed.

like image 41
James Adkison Avatar answered Aug 05 '26 10:08

James Adkison



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!