avatar
C++ pointer problem# Programming - 葵花宝典
r*2
1
大家好,
这个指针真是麻烦。有点想不明白。
我知道删除单个指针要用delete,而是数组的话,要用delete [] theArray。
但是为什么不能一个接个的delete呢,既然所有的数组都在heap上。
比如,
#include
int main()
{
int * Family = new int[5];
delete [] Family;
}
这是标准的方法。但为什么以下的方法就不行?Family+i 也是一个指针, 并且就是在
heap上呀,
#include
int main()
{
int * Family = new int[5];
for (int i=0; i<5; i++)
delete (Family+i);
}
有什么猫腻呀? 请大侠指点!
avatar
g*y
2
Why you want to do that is beyond my mind.
Think a little bit about how memory management is achieved, you should
understand why.

【在 r******2 的大作中提到】
: 大家好,
: 这个指针真是麻烦。有点想不明白。
: 我知道删除单个指针要用delete,而是数组的话,要用delete [] theArray。
: 但是为什么不能一个接个的delete呢,既然所有的数组都在heap上。
: 比如,
: #include
: int main()
: {
: int * Family = new int[5];
: delete [] Family;

avatar
S*n
3
Actually, I think radmin22 ask a good question.
The difference between, malloc/free, new/delete, and new[]/delete[]
lies in the semantic and history of C/C++.
malloc/free and new/delete differs in that, new/delete not only
malloc/free the memory area, but also call the object constructor/destructor.
And in early days of C++, if you new an array of objects, and you need
to delete them in following way.
p = new Object[size];
delete[size] p;
This delete[size] seems easily to be tra

【在 g*****y 的大作中提到】
: Why you want to do that is beyond my mind.
: Think a little bit about how memory management is achieved, you should
: understand why.

avatar
K*n
4
new int[5] 和 五次 new int 的 overhead 完全不一样。
你可以查看Family pointer - 16 到 Family pointer + 16所指的memory content。
所以
int * Family = new int[5];
for (int i=0; i<5; i++)
delete (Family+i);
是不可以的。
avatar
r*2
5
谢谢各位的答复,我明白了其中的道理。其实我最主要的问题是以下这个程序:
#include
const int DefaultSize = 10;
// declare a simple Animal class so that we can
// create an array of animals
class Animal
{
public:
Animal(int);
Animal();
~Animal() {}
int GetWeight() const { return itsWeight; }
void Display() const { cout << itsWeight; }
private:
int itsWeight;
};
Animal::Animal(int weight):
itsWeight(weight)
{}
Animal::Animal():
avatar
K*n
6
Are you sure &theZoo[k] gives an animal pointer???
相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。