extraneous calls to copy-constructor and destructor

我怕爱的太早我们不能终老 提交于 2019-12-03 21:12:18

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!