C++ 为什么不及时;“双重免费”;破坏后
我尝试在复制构造之后测试“双自由”(靠近C++ 为什么不及时;“双重免费”;破坏后,c++,oop,C++,Oop,我尝试在复制构造之后测试“双自由”(靠近AutoPtr 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 &
AutoPtr 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;
}
my gcc version 8.2.1未定义通过未指向使用
new
分配的有效对象(例如,当指针因另一次删除而无效)的指针进行删除的行为
无法保证行为未定义的程序会“提示”任何内容。您看到了什么输出?未定义的行为未定义。未定义的行为不会导致保证崩溃(所示代码实际上会在gcc 8中崩溃)。您的程序显示未定义的行为。“似乎有效”是未定义行为的一种可能表现形式。
$ ./a.out
A construct:0x781b68
1
2
AutoPtr destruct: 0x781b68
A destruct:0x781b68
AutoPtr destruct: 0x781b68
A destruct:0x781b68