释放一个指针意味着我不能像*p那样使用更多的指针

Freeing a pointer mean that I can not use more the pointer as *p?

本文关键字:指针 不能 一个 释放 意味着      更新时间:2023-10-16

我看到了这段代码。在析构函数之后使用:int area () {return (*width * *height);}是否有效?

// example on constructors and destructors
#include <iostream>
using namespace std;
class CRectangle {
    int *width, *height;
 public:
 CRectangle (int,int);
~CRectangle ();
int area () {return (*width * *height);}
};
CRectangle::CRectangle (int a, int b) {
 width = new int;//
 height = new int;//
 *width = a;//
 *height = b;//
}//
CRectangle::~CRectangle (){//
 delete width;//
 delete height;//
}////

在这段代码中,您没有在析构函数之后"使用" int area () {return (*width * *height);},您只是在析构函数之后声明了它。

然而,如果你问其他代码是否可以在对象被销毁后调用area,它不能。

使用int area () {return (*width * *height);}是否有效析构函数?

实际上你不能使用包含area方法的对象,因为它被销毁了。

的例子:

CRectangle *r = new CRectangle(100,200);
...
delete r;
r->area(); 
// There's no "r" anymore so it doesn't matter *width or *height are valid or not
// you can't access to "area" method

自由后使用*height*width绝对无效。然而,在对象被销毁之后,使用它通常也是无效的。由于指针的释放发生在析构函数中,因此可以接受。

然而,你的代码打破了"三规则":当一个类分配自己的内存时,它需要有一个复制构造函数和一个赋值操作符,否则你要么会泄漏内存,要么会"使用不应该使用的内存"(或两者兼而有之)。

考虑:

...
CRectangle r1(10,25);
CRectangle r2(10,26);
CRectangle bigger(0,0);
if (r1.area() > r2.area())
   bigger = r1;
else
   bigger = r2;
{
   CRectangle r3(200, 300);
   r1 = r3;
}   // r3 is destroyed here.
cout << r1.area() << endl;   // Bang, using freed memory. 

在复制构造函数和赋值操作符中,需要根据具体操作,从旧数据中释放相关数据,并分配新数据。

[当然,对两个整数这样做完全是浪费内存空间和时间-即使是我所知道的最好的内存分配也会比在类中只使用两个整数多使用五倍的内存。]

是的,在释放悬空指针之后,对它的尊重是未定义的行为。

您是否在问销毁对象后在对象上调用area()是否合法?

为什么你会认为你可以,应该或会!