|
|
发表于 2005-7-30 09:35:25
|
显示全部楼层
This is really a interesting question.
Here is the small test program:
[PHP]
1 #include <iostream>
2 #include <vector>
3
4 using namespace std;
5
6 class A {
7 public:
8 A() { cerr << "A contstruct " << endl; };
9 ~A() { cerr << " A destructe " << endl; }
10 };
11
12 class B {
13 public:
14 B() { cerr << "B contstruct " << endl; };
15 ~B() { cerr << " B destructe " << endl; }
16 };
17
18 int main()
19 {
20 int c =3;
21 vector<B> b(c);
22 cerr << "b capacity = " << b.capacity() << endl;
23 vector<A> a(c-1);
24 cerr << "a capacity = " << a.capacity() << endl;
25
26 cerr << " before exit " << endl;
27
28 return 0;
29 }
[/PHP]
Here is the output:
[PHP]
g++ -ggdb -o vt main.cc
-bash-2.05b$ ./vt
B contstruct
B destructe
b capacity = 3
A contstruct
A destructe
a capacity = 2
before exit
A destructe
A destructe
B destructe
B destructe
B destructe
[/PHP]
在声明vector的时候,居然调用了A,B的consturctor 和 destructor.
[PHP]
% gdb vt
) break B::~B
) bt
[/PHP]
发现vector的声明是这样的:
261 vector(size_type __n)
262 : _Base(__n, allocator_type())
263 { _M_finish = uninitialized_fill_n(_M_start, __n, value_type()); }
Ln 263, value_type 会在栈上生成一个临时对象。所以constructor 和 destructor会在声明vector的时候被调用。
DONE |
|