Search code examples
c++vectorc++17destructordynamic-memory-allocation

vector::emplace_back result to call destructor twice


Simple program is written as:

#include <iostream>
#include <vector>
using std::vector;

class Test {
public:
    Test( int d ) : data(d), addr(&data) {

    }
    // Test( Test &src ) : data(src.data), addr(src.addr) { }
    const int data;
    const int *addr;
    ~Test() {
        delete addr;
    }
    void print() {
        std::cout << " Data is : " << data << '\n';
    }
};

int main( int, char**, char** ) {

    std::vector<Test> data1;
    data1.emplace_back( 98 );

    for( auto a : data1 )
        a.print();
    std::cout << "main";
    std::cout << std::endl;
    return 0;
}

and the output was program output

Possibly the reason was the destructor called twice I tried to get some info from : here and there but cant get clear vison.


Solution

  • As mentioned in comments the problem is the delete statement in destructor which is unwanted for non-dynamic data member.