Running the following test code
int destroyed[3] = { 0, 0, 0 };
struct Test {
int a;
Test() {}
~Test() {
destroyed[a]++;
}
};
template<class T>
void remove(std::vector<T>& v, size_t i) {
std::swap(v[i], v.back());
v.pop_back();
}
main() {
std::vector<Test> vt(3);
vt[0].a = 0;
vt[1].a = 1;
vt[2].a = 2;
remove(vt, 0);
}
destroyed
counts the number of times an element has been destroyed.
I can see that destroyed = { 2, 0, 0 }
.
I want to remove element 0
, so I should destroy it. However I don't need to call its destructor twice; so, how can I write the remove
function so that I end up with destroyed = { 1, 0, 0 }
(destroying it only once)?