g++ 版本是g++ (GCC) 4.1.2 20080704 (Red Hat 4.1.2-50)
我的测试代码如下
#include <iostream>
using namespace std;
class Handle{
public:
Handle(int *p, int u):_p(p),use(u){}
~Handle(){cout << "delete" << endl; delete _p;}
void display(){cout << "value : " << *_p << ", use : " << use << endl;}
private:
int *_p;
int use;
};
int main()
{
//Test case one
{
int *i = new int(10);
Handle *h = new Handle(i, 2);
Handle *h1 = new Handle(i, 100);
h->display();
h1->display();
delete h;
delete h1;
//call ~Handle() two times, means free double times, why don't runtime error??
}
//Test case two
{
int *a = new int(11);
Handle h2(a, 23);
Handle h3(a, 33);
h2.display();
h3.display();
//in this case, will double free error
}
cout << "ok" << endl;
return 0;
}
只要有测试用例一,程序运行没有错误,但如果我添加测试二,这个程序会有双重免费错误。不知道这个错误是怎么发生的?