c++继承中拷备构造函数调用的疑问?

class Base
{
 public:
      Base()
      {
         cout << "Base()" << endl;
      }
      Base(const Base&)
      {
         cout << "Base(const Base&)" << endl;
      }
      ~Base()
      {
         cout << "~Base()" << endl;
      }
};

class Derived : public Base
{
 public:
      Derived()
      {
         cout << "Derived()" << endl;
      }
      Derived(const Derived&)
      {
         cout << "Derived(const Derived&)" << endl;
      }
      ~Derived()
      {
         cout << "~Derived()" << endl;
      }
};

int main(void)
{
    vector<Base> vec;
    Base obase;
    Derived oderived;
    vec.push_back(obase);
    vec.push_back(oderived);
    return 0;
}

结果:
Base()
Base()
Derived()
Base(const Base&)
Base(const Base&)
Base(const Base&)
~Base()
~Derived()
~Base()
~Base()
~Base()
~Base()
为什么会调用三次拷备构造函数呢?

给你看个例子你就知道怎么回事了,vector空间从1 到2 的时候,需要先释放再申请。

vector push_back() (2012-02-20 17:10:53)转载▼
标签: 杂谈 分类: c/cplusplus
class Point
{
public:
Point()
{
cout<<"construction!"< }
Point(const Point &pt)
{
cout }
~Point()
{
cout }
};
int main()
{
std::vector pointVec;
Point a; //执行构造函数一次
Point b; //执行构造函数一次
pointVec.push_back(a); //执行拷贝构造函数一次
pointVec.push_back(b); //执行拷贝构造函数两次,析构函数一次。
cout< system("pause");
return 0; //返回后, 执行四次析构函数
}
1.vector的push_back()函数的动态增长过程是:0 -> 1 -> 2 -> 4 -> 8 -> 16 -> 32 ...
2.push_back(a);//复制对象,从而会调用拷贝构造函数,空间为1.
3.push_back(b);//空间不够,增加到2, 复制a,b到新空间(执行两次构造函数)。 然后释放原来a占的空间。所以这里执行一次析构函数
4.main函数返回,执行四次析构函数。vector里面的a,b两次, main函数中的a,b两次,总共四次