push_back与构造函数

vector在push_back时,如果是自定义的数据结构,它会调用这个结果的拷贝构造函数来初始化vector中的存储空间,如果需要用push_back()需要自己实现拷贝构造函数!具体vector中是怎么push_back可以查看stl源码剖析中的具体实现。

如果注释掉test的拷贝构造函数,push_back不会调用无参构造函数,但是能够初始化,并且a的值还为10,不知道为什么。

 1 #pragma execution_character_set("utf-8")
 2 #include <iostream>
 3 #include <time.h>
 4 #include <Windows.h>
 5 #include <QDebug>
 6 #include <vector>
 7 using namespace std;
 8 struct test{
 9     int a;
10     test()
11     {
12         qDebug()<<"调用构造函数"<<endl;
13         a = 10;
14     }
15     test(const test& right)
16     {
17         qDebug()<<"调用拷贝构造函数"<<endl;
18         a = right.a;
19     }
20     test& operator=(const test& right)
21     {
22         qDebug()<<"调用赋值运算符"<<endl;
23         a = right.a;
24         return *this;
25     }
26 };
27 
28 int main(int argc, char *argv[])
29 {
30     vector<test> testArray;
31     test test1;
32     testArray.push_back(test1);
33     qDebug()<<testArray[0].a<<endl;
34 }

原文地址:https://www.cnblogs.com/AKUN-FYK/p/11806045.html