本文介绍了对复制构造函数和析构函数的无关调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

[a跟踪]

class A
{
    public:
         A()          {cout<<"A Construction"     <<endl;}
         A(A const& a){cout<<"A Copy Construction"<<endl;}
        ~A()          {cout<<"A Destruction"      <<endl;}
};

int main() {
    {
        vector<A> t;
        t.push_back(A());
        t.push_back(A());   // once more
    }
}

输出为:

A Construction        // 1
A Copy Construction   // 1
A Destruction         // 1
A Construction        // 2
A Copy Construction   // 2
A Copy Construction   // WHY THIS?
A Destruction         // 2
A Destruction         // deleting element from t
A Destruction         // deleting element from t
A Destruction         // WHY THIS?


推荐答案

为清楚地了解发生了什么,我建议将在输出中使用 this 指针来标识哪个A正在调用该方法。

To clearly see what's going on, I recommend include the this pointer in the output to identify which A is calling the method.

     A()          {cout<<"A (" << this << ") Construction"     <<endl;}
     A(A const& a){cout<<"A (" << &a << "->" << this << ") Copy Construction"<<endl;}
    ~A()          {cout<<"A (" << this << ") Destruction"      <<endl;}

我得到的输出是

A (0xbffff8cf) Construction
A (0xbffff8cf->0x100160) Copy Construction
A (0xbffff8cf) Destruction
A (0xbffff8ce) Construction
A (0x100160->0x100170) Copy Construction
A (0xbffff8ce->0x100171) Copy Construction
A (0x100160) Destruction
A (0xbffff8ce) Destruction
A (0x100170) Destruction
A (0x100171) Destruction

所以流程可以解释为:


  1. 创建了临时A(…cf)。

  2. 将临时A(…cf)复制到向量(…60)。

  3. 临时A(…cf)被破坏。

  4. 另一个临时A(…ce)被创建。

  5. 展开向量,并将该向量中的旧A(…60)复制到新位置(…70)

  6. 另一个临时A( …ce)被复制到向量(…71)中。

  7. 所有不必要的A副本(... 60,…ce)现在都被销毁。

  8. 向量被破坏了,所以里面的A(…70,…71)也被破坏了。

  1. The temporary A (…cf) is created.
  2. The temporary A (…cf) is copied into the vector (…60).
  3. The temporary A (…cf) is destroyed.
  4. Another temporary A (…ce) is created.
  5. The vector is expanded, and the old A (…60) in that vector is copied to the new place (…70)
  6. The other temporary A (…ce) is copied into the vector (…71).
  7. All unnecessary copies of A (…60, …ce) are now destroyed.
  8. The vector is destroyed, so the A's (…70, …71) inside are also destroyed.

如果您

    vector<A> t;
    t.reserve(2); // <-- reserve space for 2 items.
    t.push_back(A());
    t.push_back(A());

输出将变为:

A (0xbffff8cf) Construction
A (0xbffff8cf->0x100160) Copy Construction
A (0xbffff8cf) Destruction
A (0xbffff8ce) Construction
A (0xbffff8ce->0x100161) Copy Construction
A (0xbffff8ce) Destruction
A (0x100160) Destruction
A (0x100161) Destruction

这篇关于对复制构造函数和析构函数的无关调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 13:51