zoukankan      html  css  js  c++  java
  • STL容器与拷贝构造函数

    所有容器提供的都是“value语意”而非“reference语意”。容器内进行元素的安插操作时,内部实施的是拷贝操作,置于容器内。因此STL容器 的每一个元素都必须能够拷贝。---<<C++标准程序库>> 侯捷、孟岩译 p144页原文 

    以vector为例,往Vector中(实际上所有STL容器都是这样)放元素,Vector会调用元素类的拷贝构造函数生成的副本,当 Vector走出生存期时(),会自动调用其中每个元素的析构函数。比如,如果 vector<myclass> a,然后a.push_back(b);push_back其实是调用myclass的拷贝构造函数将参数b拷贝进去的。由于vector是自动管理的, 出了a的作用域外,a会自动消失释放内存。之前push_back到a里面的数据b通过调用b.~myclass()释放内存。

    1. #include <vector>   
    2. using namespace std;   
    3.   
    4. class CDemo{   
    5. public:   
    6. CDemo():str(NULL){}   
    7. ~CDemo(){if(str) delete [] str;}   
    8. char *str;   
    9. };   
    10.   
    11. int main()   
    12. {   
    13. CDemo d1;   
    14. d1.str = new char[32];   
    15. strcpy(d1.str, "trend micro");   
    16.   
    17. vector <CDemo> *a1 = new vector <CDemo>();   
    18. a1 -> push_back(d1);   
    19.   
    20. delete a1;   
    21. return 0;   
    22. }   

    1. vector <CDemo> *a1 = new vector <CDemo>(); a1是new出来的,所以必须要手工delete.这是对a1本身而言,而与a1内存储的数据无关。
    2. a1 -> push_back(d1); 这部操作比较复杂,因为你的vector是存储类,而不是类指针。但是push_back的参数是引用,所以不需要创建d1的拷贝(也就不需要调用拷贝构 造)作为参数传递给push_back。但是在push_back中,会创建d1的拷贝d1_1(需要调用拷贝构造),d1_1是存储在a1管理的内存 中。
    3. delete a1; a1中存有d1_1,所以会删除d1_1,自然会调用d1_1的析构函数。
    4. 在main中return 0, d1被自动删除,此时调用d1的析构函数。
    5. 因为class CDemo没有拷贝构造函数,所以创建拷贝时只是简单的把新对象中每个成员变量的值设置成与原来的对象相等。相当于运行memcpy。这时问题就来了,因 为你的一个成员是char *str; 这样d1,d1_1的str都是指向同一个地址。所以只有第一次调用CDemo的析构函数时能运行正确,以后的都会出错。因为一个地址只能释放一次。

    解决办法是定义自己的拷贝构造函数实现深拷贝:

    1. #include <iostream>  
    2. #include <fstream>  
    3. #include <vector>  
    4. using namespace std;  
    5.   
    6. ofstream out("test.out");  
    7. class CDemo{  
    8. public:  
    9.     CDemo():str(NULL){  
    10.         out << "constructor is called" << endl;  
    11.     }  
    12.     CDemo(const CDemo &cd)  
    13.     {  
    14.         out << "copy constructor is called" << endl;  
    15.         this->str = new char[strlen(cd.str)+1];  
    16.         strcpy(str, cd.str);  
    17.     }  
    18.   
    19.     ~CDemo(){  
    20.         if(str){  
    21.             out << "destructor is called" << endl;  
    22.             delete[] str;  
    23.         }  
    24.     }  
    25.     char *str;  
    26. };  
    27.   
    28. int main()  
    29. {  
    30.     vector <CDemo> *a1 = new vector <CDemo>();  
    31.     a1 -> reserve(1);  
    32.     out << a1 -> capacity() << endl;  
    33.       
    34.     CDemo d1;  
    35.     d1.str = new char[32];  
    36.     strcpy(d1.str, "trend micro1");  
    37.     out << "/////////////////////////////////" << endl;  
    38.     a1->push_back(d1);  
    39.     out << "/////////////////////////////////" << endl;  
    40.     CDemo d2;  
    41.     d2.str = new char[32];  
    42.     strcpy(d2.str, "trend micro2");  
    43.     out << "/////////////////////////////////" << endl;  
    44.     a1->push_back(d2);  
    45.     out << "/////////////////////////////////" << endl;  
    46.     delete a1;  
    47.   
    48.     return 0;  
    49. }  

    1
    constructor is called
    /////////////////////////////////
    copy constructor is called
    /////////////////////////////////
    constructor is called
    /////////////////////////////////
    copy constructor is called
    copy constructor is called         //搬运之前的元素
    destructor is called                    //之前的元素被析构
    /////////////////////////////////
    destructor is called                    //析构容器中所有对象
    destructor is called
    destructor is called                    //析构CDemo d1
    destructor is called                   //析构CDemo d2

    可以看到,再加入第二个对象的时候,拷贝构造函数被调用的两次,这是因为,在第一次push_back时,vector的capacity是1,是 正常调用一次拷贝构造;而第二次push_back时,会发现容量不够了,stl会重新分配一个old_size的两倍的空间,除了新push进来的数据 会放在这个新空间,调用一次拷贝构造,原来已经有的数据也要搬过来的,就又要调用拷贝构造。如果把a1 -> reserve(1);修改为a1 -> reserve(2);保证第二次时也有足够的空间,那么程序的运行结果为:

    2
    constructor is called
    /////////////////////////////////
    copy constructor is called
    /////////////////////////////////
    constructor is called
    /////////////////////////////////
    copy constructor is called
    /////////////////////////////////
    destructor is called
    destructor is called
    destructor is called
    destructor is called
    为了进一步验证空间重新分配对对象拷贝的影响,看下面的例子:

    1. #include <iostream>  
    2. #include <fstream>  
    3. #include <vector>  
    4. using namespace std;  
    5.   
    6. ofstream out("test.out");  
    7. class CDemo{  
    8. public:  
    9.     CDemo():str(NULL){  
    10.         out << "constructor is called" << endl;  
    11.     }  
    12.     CDemo(const CDemo &cd)  
    13.     {  
    14.         out << "copy constructor is called" << endl;  
    15.         this->str = new char[strlen(cd.str)+1];  
    16.         strcpy(str, cd.str);  
    17.     }  
    18.   
    19.     ~CDemo(){  
    20.         if(str){  
    21.             out << "destructor is called" << endl;  
    22.             delete[] str;  
    23.         }  
    24.     }  
    25.     char *str;  
    26. };  
    27.   
    28. int main()  
    29. {  
    30.     vector <CDemo> *a1 = new vector <CDemo>();  
    31.     a1 -> reserve(1);  
    32.       
    33.     for(int i = 1; i < 5; i ++){  
    34.         out << "/////////////////////////////////" << endl;  
    35.         out << i << endl;  
    36.         CDemo d;  
    37.         d.str = new char[32];  
    38.         strcpy(d.str, "trend micro1" + i);  
    39.         out << "begin to push_back" << endl;  
    40.         out << "the vector capacity is " << a1 -> capacity() << endl;  
    41.         a1->push_back(d);  
    42.     }  
    43.     out << "/////////////////////////////////" << endl;  
    44.     delete a1;  
    45.   
    46.     return 0;  
    47. }  

    程序的运行结果:

    /////////////////////////////////
    1
    constructor is called
    begin to push_back
    the vector capacity is 1
    copy constructor is called
    destructor is called
    /////////////////////////////////
    2
    constructor is called
    begin to push_back
    the vector capacity is 1
    copy constructor is called
    copy constructor is called          //搬运之前的元素1
    destructor is called                     //之前的元素被析构
    destructor is called                     //CDemo d临时对象
    /////////////////////////////////
    3
    constructor is called
    begin to push_back
    the vector capacity is 2
    copy constructor is called
    copy constructor is called         //搬运之前的元素1
    copy constructor is called         //搬运之前的元素2
    destructor is called                    //之前的元素1被析构
    destructor is called                    //之前的元素2被析构
    destructor is called                    //CDemo d临时对象
    /////////////////////////////////
    4
    constructor is called
    begin to push_back
    the vector capacity is 4
    copy constructor is called         //不需要搬运,第三次时容量已经变成4
    destructor is called                    //CDemo d临时对象
    /////////////////////////////////
    destructor is called                    //析构容器中所有对象
    destructor is called
    destructor is called
    destructor is called
    可以看到,容量的确是按照两倍的空间递增,并且原来已经有的数据要搬过来,就要调用拷贝构造。所以为了程序的效率,最好一开始就用reserve确定vector的大小,避免之后动态扩展,搬运原有数据引起拷贝构造的调用。

  • 相关阅读:
    Android 中Base64的操作
    android 异步图片处理 工具类
    android 跨应用跳转 启动其他应用指定界面
    C++代码案例
    Android 中 Base64的操作应用
    Python基础笔记1
    [linux] 大批量删除任务
    Python基础笔记3
    [R] 如何快速生成许多差异明显的颜色?
    Python基础笔记4
  • 原文地址:https://www.cnblogs.com/wuchanming/p/3735971.html
Copyright © 2011-2022 走看看