2012-09-16 30 views
2

我有以下代码[这是一个面试问题]:C++默认情况下,复制和推广的构造

#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。有人可以解释这个输出吗?

谢谢。

+0

请回复评论或提出新问题。这是一个新问题,不是吗? –

+0

是的,编辑是一个单独的问题;我曾尝试保留()。 – Jake

+0

他们的确切顺序 - http://ideone.com/TUEGo –

回答

4

基础默认构造函数从线

cont.push_back(B(1)); 

你所有的B构造函数调用默认的构造函数A调用一次。最后两个拷贝构造函数是由于向量重新分配。例如,如果你的push_back年代以前添加

cont.reserve(3); 

,他们会自行消失。

之前的那个是您最后的push_back中临时A(2)的副本。

+0

除了具有足够大的矢量以便不调整大小外,还要注意:如果您在优化开启的情况下进行编译,那么随着编译器优化它们,几个拷贝构造函数会消失。 –

+0

为何A(2)的push_back具有序列:基本副本构造函数 基地振兴构造函数,基地拷贝构造函数,而A(1)的push_back只是有:基地振兴构造函数,基地拷贝构造函数 – Jake

+0

@Jake你订? –