标签:class div code c size t sp string color int ble
看一个小例子:
1 |
#include <iostream> |
2 |
3 |
using namespace
std; |
4 |
5 |
class A { |
6 |
public : |
7 |
A() { cout << "A::A()"
<< endl; } |
8 |
~A() { cout << "A::~A()"
<< endl; } |
9 |
}; |
10 |
11 |
int main() { |
12 |
A* a = new
A[5]; |
13 |
delete [] a; |
14 |
15 |
return
0; |
16 |
} |
编译执行输出:
A::A() A::A() A::A() A::A() A::A() A::~A() A::~A() A::~A() A::~A() A::~A()
上面的输出显示程序正确释放了5个A对象。
现在的问题是:我们在delete[]
a语句中并没有给出对象数组的大小,那么系统是如何做到正确释放对象个数的呢?
接着看下面的程序段:
1 |
#include <iostream> |
2 |
3 |
using namespace
std; |
4 |
5 |
class A { |
6 |
public : |
7 |
A() { cout << "A::A()"
<< endl; } |
8 |
~A() { cout << "A::~A()"
<< endl; } |
9 |
}; |
10 |
11 |
int main() { |
12 |
A* a = new
A[5]; |
13 |
14 |
int
addr = ( int )a - 4; |
15 |
cout << "delete[] size = "
<< *( int *)addr << endl; |
16 |
17 |
delete [] a; |
18 |
19 |
return
0; |
20 |
} |
编译执行:
A::A() A::A() A::A() A::A() A::A() delete[] size = 5 A::~A() A::~A() A::~A() A::~A() A::~A()
结论:
系统在new一个数组对象的时候会把数组大小存放在返回的内存地址的前4个字节中。
c++: 获取delete[]中的数组大小,布布扣,bubuko.com
标签:class div code c size t sp string color int ble
原文地址:http://www.cnblogs.com/lidabo/p/3701097.html