簡體   English   中英

對copy-constructor和析構函數的無關調用

[英]extraneous calls to copy-constructor and destructor

[跟進這個問題 ]

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正在調用該方法。

     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)也被破壞。

如果你這樣做,第5步將會消失

    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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM