[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:
- The temporary A (…cf) is created.
- The temporary A (…cf) is copied into the vector (…60).
- The temporary A (…cf) is destroyed.
- Another temporary A (…ce) is created.
- The vector is expanded, and the old A (…60) in that vector is copied to the new place (…70)
- The other temporary A (…ce) is copied into the vector (…71).
- All unnecessary copies of A (…60, …ce) are now destroyed.
- 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
精彩评论