[英]C++ default, copy and promotion constructor
I have the following code [This is an interview question]: 我有以下代码[这是一个面试问题]:
#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;
}
The output is : 输出为:
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
I am having trouble understanding this output, specifically why base default is called once and the last 3 copy ctor. 我在理解此输出时遇到了麻烦,特别是为什么为什么一次调用基本默认值,最后一次调用3个副本ctor。 Can someone please explain this output ?
有人可以解释这个输出吗?
Thanks. 谢谢。
The base default constructor is called once from the line 基本默认构造函数从该行调用一次
cont.push_back(B(1));
All your B
constructors call the default A
constructor. 您所有的
B
构造函数都调用默认的A
构造函数。 The last two copy constructors are because of a vector re-allocation. 最后两个副本构造函数是由于向量的重新分配。 For example, if you added
例如,如果您添加了
cont.reserve(3);
before the push_back
s, they'd go away. 在
push_back
之前,它们会消失。
The one before that is a copy of the temporary A(2)
in your final push_back
. 之前的一个是您最终的
push_back
中的临时A(2)
的副本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.