- 论坛徽章:
- 2
|
一个使用STL vector的例子,
C++ 代码如下:
编译运行后输出:
created!
destroyed!
=============
size of a = 5
created!
destroyed!
destroyed!
destroyed!
destroyed!
destroyed!
++++++++++++
destroyed!
destroyed!
destroyed!
destroyed!
destroyed!
destroyed!
destroyed!
问题:
1. Vector<Object> a(5)为什么只调用一次 Object 的构造函数,而且还调用了一次析构函数? Object a[5]是调用5次构造函数
2. push_back 一个元素后为什么调用多次析构函数?
- #include <iostream>
- #include <vector>
- #include <list>
- using namespace std;
- class Object {
- public:
- int a;
- public:
- Object() {
- cout << "created!" << endl;
- }
- ~Object() {
- cout << "destroyed!" << endl;
- }
- };
- int main(void) {
- vector<Object> a(5);
- //Object a[5];
- cout << "=============" << endl;
- cout << "size of a = " << a.size() << endl;
- Object tmp;
- tmp.a = 12;
- a.push_back(tmp);
- cout << "++++++++++++" << endl;
- return 0;
- }
复制代码 |
|