1

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.

Sudip Ghimire
  • 677
  • 6
  • 15
  • 5
    `delete addr;` twice? Must be a typo. Anyway, you should only call `delete` on a pointer that was `new`ed. – cigien Jun 13 '20 at 14:28
  • 4
    `addr` is not a pointer that was returned from `new`. Passing it to `delete` has undefined behaviour. Why do you think you need to `delete` anything? (`delete` is not for getting rid of pointers, it's for getting rid of what they point to, and *only* if that thing was created on the free store with `new`.) – molbdnilo Jun 13 '20 at 14:30
  • oh! that was where i went wrong. Yes I was assuming that when deafult constructor is called it dynamically assign the address. Anyway It is solved now. – Sudip Ghimire Jun 13 '20 at 14:41

1 Answers1

2

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

Sudip Ghimire
  • 677
  • 6
  • 15