STL中list和vector在添加元素时push_back会调用拷贝构造函数


 1 #include <iostream>
 2 #include <list>
 3 #include <vector>
 4 #include <cstring>
 5 using namespace std;
 6 
 7 class B
 8 {
 9 public:
10     B()
11     {
12         cout<<"B()"<<endl;
13     }
14     void print()
15     {
16         cout<<"print"<<endl;
17         p = NULL;
18         len = 0;
19     }
20     B(const B& b)
21     {
22         cout<<"copy B()"<<endl;    
23         if(p)
24         {
25             delete b.p;
26             len = len;
27             p = new char[len];
28             memcpy(p, b.p, len);
29         }
30     }
31     ~B()
32     {
33         cout<<"~B()"<<endl;
34         if(p)
35         {
36             delete []p;    
37             p = NULL;
38             len = 0;
39         }
40     }
41     char *p;
42     int len;
43     
44 };
45 
46 int main()
47 {
48     list<B> ls;
49     vector<B> vec;
50     B b;
51     ls.push_back(b);
52     vec.push_back(b);
53     return 0;
54 }

执行结果:

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM