LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 1152|回复: 3

vector在创建的时候怎么回调用元素的析构函数呢?

[复制链接]
发表于 2005-7-29 08:40:35 | 显示全部楼层 |阅读模式
我在代码里写了这样的句子

std::vector<mPoint> point(i);
std::vector<Board> bd(i-1);

mPoint和Board分别是两个类,运行到这里的时候,竟然调用了这连个累得析构函数。为什么呢?
发表于 2005-7-29 20:27:11 | 显示全部楼层
1. 什么叫"这连个累得析构函数"?
2. 所谓的创建的时候怎么会调用析构函数?
回复 支持 反对

使用道具 举报

 楼主| 发表于 2005-7-30 08:17:39 | 显示全部楼层
是“这两个类”,至于为什么调用,我也不知道,反正调试的时候跑到了析沟函数。
回复 支持 反对

使用道具 举报

发表于 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
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表