By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,750 Members | 1,199 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,750 IT Pros & Developers. It's quick & easy.

more about vectors

P: n/a
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?

--
Lasse
Jul 19 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
"Lasse Skyum" <no spam> wrote:

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
Jul 19 '05 #2

P: n/a


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.

--
Lasse
Jul 19 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.