more about vectors

L

Lasse Skyum

Suppose i have a std::vector containing 2 elements. If I delete the first
element, the second element will be copied to the first position. A little
test showed that the deleted element was indeed destructed, but there was
never executed a copy-constructor for moving the remaining element??


class CMyClassA
{
public:
CMyClassA(){printf("+");} // construct

CMyClassA(const CMyClassA &a){printf("c");} // copy construct

virtual ~CMyClassA(){printf("-");} // destruct
};

void test(){
CMyClassA q;
vector<CMyClassA> a;
a.push_back(q); // Insert two elements
a.push_back(q);
printf("|");
a.erase(a.begin(),a.begin()+1); // Remove the first element
printf("|");
}

This test prints "+ccc-|-|--" , but I would have expected there to be a 'c'
somewhere between the two | |.

Can anyone explain this?
 
M

Max M

Lasse Skyum said:
Suppose i have a std::vector containing 2 elements. If I delete the first
element, the second element will be copied to the first position. A little
test showed that the deleted element was indeed destructed, but there was
never executed a copy-constructor for moving the remaining element??

How can you know the destructed object is indeed the erased element?
I guess the values are shifted through assignment, and then the last
element is destructed. (Redefine assignment to keep track of when it gets
called, and print the object's address to know who gets really destructed.)

Max
 
L

Lasse Skyum

How can you know the destructed object is indeed the erased element?

Hmmm... guess that was kind of an assumption...
I guess the values are shifted through assignment, and then the last
element is destructed. (Redefine assignment to keep track of when it gets
called, and print the object's address to know who gets really
destructed.)

Yes, you are right! The element is simply assigned, not destructed and
copy-constructed again as I thought it would be.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top