鉴于这种一小段代码:断言这两个指针指向NULL不发生后删除()
#include <iostream>
#include <assert.h>
using namespace std;
struct Foo
{
// something
};
int main()
{
Foo *p1 = new Foo;
Foo * p2 = p1;
assert(NULL != p1);
delete p1;
p1 = NULL;
assert(NULL != p2);
delete p2;
cout << "everything is cool!" << endl;
return 0;
}
当我删除p1
,第二断言(assert(NULL != p2);
)没有失败,为什么?
输出:everything is cool!
那么为什么p2
断言不会失败?
因为p2仍然设置为p1所具有的地址。在更改之后,它不会获得p1的值。 – drescherjm