释放一个指针意味着我不能像*p那样使用更多的指针
Freeing a pointer mean that I can not use more the pointer as *p?
我看到了这段代码。在析构函数之后使用: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()
是否合法?
。
为什么你会认为你可以,应该或会!
相关文章:
- 为什么"具有常量成员的结构"类型的指针不能指向"具有非常量成员的结构"?
- 为什么智能指针不能用通常的指针方式声明
- 智能指针不能自动用作原始指针
- MPI_Op_create:候选功能不可行.自定义结构指针不能解释为空指针
- 为什么指针不能指向张贴增量,而可以这样做才能预先递增
- 为什么引用和指针不能一起使用?
- 为什么指向非静态成员函数的指针不能用作标准库算法的一元谓词
- 为什么指向函数的指针不能绑定到左值引用,而函数可以?
- 为什么基类型指针不能获取派生类对象的地址值?
- 错误:声明冲突 - 指针不能是 int
- 为什么指向非常量成员函数的指针不能指向常量成员函数和相反的函数?
- 为什么智能指针不能在其构造函数中为我调用 new()?
- 基类指针不能分配给派生类指针的原因
- c++继承问题,基类指针不能指向子类
- 函数指针-不能更改函数签名,我有什么选择
- 为什么指针不能转换为引用
- 返回指针不能正常工作
- 为什么常量指针不能是常量表达式?
- 为什么非初始化类对象指针可以访问指针成员,而结构指针不能访问指针变量
- 为什么指向不同char类型的指针不能混合,而不同char类型的变量可以相互转换