c++ 中 delete p与 delete []p的区别

时间:2021-01-17 16:48:32

#include <cstdio>

class A
{
private:
int i;
public:
~A() { printf("hi"); }
};
void d(A *);
int main(int argc, char* argv[])
{
A *p = new A[10];
d(p);
return 0;
}

void d(A *p)
{
delete p;
}

输出结果 hi

#include <cstdio>

class A
{
private:
int i;
public:
~A() { printf("hi"); }
};
void d(A *);
int main(int argc, char* argv[])
{
A *p = new A[10];
d(p);
return 0;
}

void d(A *p)
{
delete []p;
}

输出结果hihihihihihihihihihi

结论:delete []p释放指向对象的指针空间  为每一个对象调用析构函数