开发者

extraneous calls to copy-constructor and destructor

开发者 https://www.devze.com 2022-12-27 00:24 出处:网络
[a follow up to this question] class A { public: A(){cout<<\"A Construction\"<<endl;} A(A const& a){cout<<\"A Copy Construction\"<<endl;}

[a follow up to this question]

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
    }
}

The output is:

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 el开发者_Go百科ement from t
A Destruction         // deleting element from t
A Destruction         // WHY THIS?


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;}

The output I've got is

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

So the flow can be interpreted as:

  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.

Step 5 will be gone if you do

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

The output will become:

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
0

精彩评论

暂无评论...
验证码 换一张
取 消