testobj.h:
#ifndef __TESTOBJ_H
#define __TESTOBJ_H
#include <iostream>
class TestObj{
private:
int *p;
public:
static int count;
TestObj(){
p = new int(1);
count++;
std::cout << "init p" << std::endl;
};
TestObj(const TestObj & obj){
p = new int(1);
count++;
std::cout << "copy p" << std::endl;
};
~TestObj(){
if (p != NULL){
delete p;
p = NULL;
std::cout << "delete p , p="<< p<< std::endl;
}
};
};
int TestObj::count = 0;
#endif
test.cc
#include <iostream>
#include <vector>
#include <windows.h>
#include "testobj.h"
using namespace std;
int main(){
vector<TestObj> objvector;
//objvector.reserve(10);
TestObj obj1;
objvector.push_back(obj1);
Sleep(1000);
cout << "------------" << endl;
TestObj obj2;
objvector.push_back(obj2);
Sleep(1000);
cout << "------------" << endl;
TestObj obj3;
objvector.push_back(obj3);
Sleep(1000);
cout << "------------" << endl;
cout << "Count:" << TestObj::count << endl;
}
运行结果为:
init p
copy p
------------
init p
copy p
delete p , p=00000000
copy p
------------
init p
copy p
copy p
delete p , p=00000000
delete p , p=00000000
copy p
------------
Count:9
delete p , p=00000000
delete p , p=00000000
delete p , p=00000000
delete p , p=00000000
delete p , p=00000000
delete p , p=00000000
按道理来说应该是3次普通的对象创建,和三次对象的复制构造,但是结果却多出了3次对象的复制构造。下面来分析原因。
首先得了解std::vector的元素存放方式,std::vector是以连续的方式存放数据的,当添加一个元素时,如果容器的空间不足,std::vector就需要重新分配存储空间,用来存放原来的元素和新添加的元素,存放在旧存储空间中的元素被复制到新的存储空间,接着插入新的元素,最后撤销旧的存储空间。如果提前就预分配了足够的空间(objvector.reserve(10);),就不会有额外的复制操作。下图说明了以上运行结果的行为:
最后的6个析构是创建的3个Testobj对象和objvector中的3个Testobj对象的析构。