[英]C++ default, copy and promotion constructor
我有以下代碼[這是一個面試問題]:
#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)
的副本。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.