明明白白c++ 解读effective c++系列一(条目1-5)(二)

2014-11-24 02:34:45 · 作者: · 浏览: 3
testInt();
void testClass();

int main()
{
testInt();
testClass();
}

void testInt()
{
int *p;
int *q;

p = new int[10];
q = (int*)malloc(sizeof(int)*10);

p[1] = 10;
q[1] = 10;

delete []p;
free(q);

cout< cout< }

void testClass()
{
A *p = new A[10];
p[1].a = 10;

delete p;
cout< }

#include
#include
using namespace std;

class A
{
public:
int a;
};

void testInt();
void testClass();

int main()
{
testInt();
testClass();
}

void testInt()
{
int *p;
int *q;

p = new int[10];
q = (int*)malloc(sizeof(int)*10);

p[1] = 10;
q[1] = 10;

delete []p;
free(q);

cout< cout< }

void testClass()
{
A *p = new A[10];
p[1].a = 10;

delete p;
cout< }
输出的结果是
1629738516
0
10
可以看到类里面没有释放完。
因为malloc和free都是指定大小的,你分配的时候的大小是知道的,free只用把对应的空间释放掉就可以了。
而new的时候,要分两种情况,new 一个对象,还是new[]分配对象数组。
所以 delete要明确的告诉是一个对象,还是对象数组。