C++默认、复制和提升构造函数

C++ default, copy and promotion constructor

本文关键字:构造函数 复制 默认 C++      更新时间:2023-10-16

我有以下代码[这是一个面试问题]:

#include <iostream>
#include <vector>
using namespace std;
class A{
public:
    A(){
        cout << endl << "base default";
    }
    A(const A& a){
        cout << endl << "base copy ctor";
    }
    A(int) { 
        cout << endl << "base promotion ctor";
    }
};
class B : public A{
public:
    B(){
         cout << endl << "derived default";
    }
    B(const B& b){
         cout << endl << "derived copy ctor";
    }
    B(int) {
         cout << endl << "derived promotion ctor";
    }
};
int main(){
    vector<A> cont;
    cont.push_back(A(1));
    cont.push_back(B(1));
    cont.push_back(A(2));
        return 0;
    }

输出为:

base promotion ctor
base copy ctor
base default
derived promotion ctor
base copy ctor
base copy ctor
base promotion ctor
base copy ctor
base copy ctor
base copy ctor

我无法理解此输出,特别是为什么调用一次基本默认值和最后 3 个副本 ctor。有人可以解释一下这个输出吗?

谢谢。

从行调用一次基本默认构造函数

cont.push_back(B(1));  

所有B构造函数都调用默认构造函数A构造函数。最后两个复制构造函数是因为向量重新分配。例如,如果您添加了

cont.reserve(3);

push_back之前,他们会离开。

前面的那个是你最终push_back中临时A(2)的副本。