-4

I try to test "double free" after copy construction (near AutoPtr<A> p_b = p_a) , but ./a.out do not prompt it.

#include <iostream>

using namespace std;

class A {
public:
    A(int i = 0) { cout << "A construct:" << this << endl; }
    ~A() { cout << "A destruct:" << this << endl; }
    void print() { cout << n << endl; }
    int n;

};

template<typename T>
class AutoPtr {
public:
    AutoPtr(T *p= NULL): ptr(p) {}

    ~AutoPtr() {
        cout << "AutoPtr destruct: " << ptr << endl;
        delete ptr;
    }

    T &operator*(void) const {
        return *ptr;
    }

    T *operator->(void) const {
        return &**this;
    }

private:
    T *ptr;

};

int main(void)
{
    AutoPtr<A> p_a(new A(0));
    ++p_a->n;
    p_a->print();
    AutoPtr<A> p_b = p_a;
    ++p_b->n;
    p_b->print();

    return 0;
}

terminal output:

$ ./a.out
A construct:0x781b68
1
2
AutoPtr destruct: 0x781b68
A destruct:0x781b68
AutoPtr destruct: 0x781b68
A destruct:0x781b68

my gcc version 8.2.1

Charles
  • 59
  • 5

1 Answers1

1

The behaviour of deleting through a pointer that doesn't point to a valid object (such as when the pointer was invalidated by a another deletion) allocated using new is undefined.

There is no guarantee that the program whose behaviour is undefined would "prompt" anything.

eerorika
  • 181,943
  • 10
  • 144
  • 256