读书人

为什么释放的地址还能够继续使用?该怎

发布时间: 2012-03-01 10:25:47 作者: rapoo

为什么释放的地址还能够继续使用?
在HP-UX和Linux都出现过此现象:
class A
{
public:
A(const int i):value(i){}
void print() const
{
cout << "Now Print " << this << endl;
// cout << value << endl; // 如果加此句,则在delete之后再输出会出core
}
private:
int value;
};

int main()
{
A *a = new A(4);
a->print();

A *b = new A(5);
b->print();

delete a;
a = NULL;
a->print();

delete b;
b = NULL;
b->print();

cout << "My god!" << endl;
}
输出:
Now Print 0x804a008
Now Print 0x804a018
Now Print 0
Now Print 0
My god!

加上cout << value << endl;一句后,输出:
Now Print 0x804a008
4
Now Print 0x804a018
5
Now Print 0
Segmentation fault(出core了)

不明白的就是为什么地址变为NULL之后还能继续调用类的成员呢?不论a和b对象那个先释放都是这样,请高手帮忙分析一下,谢谢

[解决办法]
类成员函数 不管有没有建立类对象都是已经存在的函数了

类对象只是提供了 this 指针,不用到的话,根本不会出错,除非是 虚函数调用
[解决办法]
编译时代码就绑定好了:
b->print(); 实际上是 print_void_const_void@@A (具体重命名规则不是这样,举例而已)

void print() const
{
// this只是输出指针值,不会有任何问题 即使this == NULL
cout < < "Now Print " < < this < < endl;
// cout < < value < < endl; // 如果加此句,则在delete之后再输出会出core
// 这句等价于 cout << this->value << endl; 要取this指向地址的内容了! 当然会出现段错误(linux) 或者 访问违例(windows)
}


[解决办法]
print()是非虚成员函数。跟对象绑定。虚成员函数跟类绑定。你可以试试把print改成虚函数,应该就不能访问了。
[解决办法]
改成virtual函数后会出现段错误

C/C++ code
#include <iostream>using namespace std;class A{   public:  A(){}  virtual void f()  {    cout<<"ok"<<endl;  }};int main(){  A *a=NULL;  a->f();  return 0;}
[解决办法]
类对象占用的内存包括类成员变量,虚函数指针。
而成员函数并不在类对象内存中。

读书人网 >C++

热点推荐