2

[この質問のフォローアップ]

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?
4

1 に答える 1

16

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
于 2010-04-17T08:32:47.447 に答える