前言

STL的容器模板类在添加元素的时候,采用拷贝构造,并且是浅拷贝,而不是直接传递指针,这意味这系统要多开辟一块内存来满足容器的使用。如果要正确使用STL容器对各种对象操作要注意重载拷贝构造函数,也就是变成深拷贝

使用细节

测试代码使用到了vector向量,而每次他都调用当前元素相应个数的析构以及拷贝构造。这其中的原因是vector初始化大小为1,然后每次添加元素进去它都会改变大小来满足元素个数的需要,而当添加到第三个的时候它大小直接开辟两个,后面变为4个(如例输出)。这就和数据结构中顺序表具体操作有关,大胆猜测一下这个大小当到达某个阈值时就会线性增加,而不会翻倍


测试代码

#include <iostream>
#include <fstream>
#include <cstring>
#include <vector>
using namespace std;

class STL_Test{
public:
    char *str;
    
public:
    STL_Test():str(NULL){
        cout << "构造函数调用" << endl;
    }
    STL_Test(const STL_Test &cd)
    {
        cout << "拷贝函数调用 " << endl;
        this->str = new char[strlen(cd.str)+1];
        strcpy(str, cd.str);
    }

    ~STL_Test(){
        if(str){
            cout << "析构函数调用,str不为null" << endl;
            delete[] str;
        }else {
            cout << "析构函数" << endl;
        }
    }
};

int main()
{
    vector <STL_Test> a2;// = new vector <STL_Test>();
    vector <STL_Test> *a1 = &a2;
    a1 -> reserve(1);
    cout << "容器大小: " << a1 -> capacity() << endl;

    STL_Test d1;
    d1.str = new char[32];
    strcpy(d1.str, "copy1");
    cout << "---------------------------------" << endl;
    a1->push_back(d1);
    cout << "---------------------------------" << endl;
    
    STL_Test d2;
    d2.str = new char[32];
    strcpy(d2.str, "copy2");
    cout << "---------------------------------" << endl;
    cout << a1 <<endl;
    a1->push_back(d2);
    cout << "容器大小: " << a1 -> capacity() << endl;
    cout << a1 <<endl;
    cout << "---------------------------------" << endl;
    
    STL_Test d3;
    d3.str = new char[32];
    strcpy(d3.str, "copy3");
    cout << "---------------------------------" << endl;
    cout << a1 <<endl;
    (*a1).push_back(d3);
    cout << "容器大小: " << a1 -> capacity() << endl;
    cout << a1 <<endl;
    cout << "---------------------------------" << endl;
    
    STL_Test d4;
    d4.str = new char[32];
    strcpy(d4.str, "copy4");
    cout << "---------------------------------" << endl;
    cout << a1 <<endl;
    a2.push_back(d4);
    a2.push_back(d4);
    cout << "容器大小: " << a2.capacity() << endl;
    cout << a1 <<endl;
    cout << "---------------------------------" << endl;
    
//  delete a1;这里删除a2栈内存空间,让程序不能正常结束

    return 0;
}