我尝试在复制构造(接近)之后测试“ double free ” AutoPtr<A> p_b = p_a
,但是./a.out不提示它。
#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;
}
终端输出:
$ ./a.out
A construct:0x781b68
1
2
AutoPtr destruct: 0x781b68
A destruct:0x781b68
AutoPtr destruct: 0x781b68
A destruct:0x781b68
我的 gcc 版本 8.2.1
通过使用分配的不指向有效对象的指针(例如,当指针因另一个删除而无效时)进行删除的行为new
是未定义的。
无法保证行为未定义的程序会“提示”任何内容。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句