0

I was thinking about this question for a while. When I tried to find answers on some websites, I found nothing. So the question is: if we have a vector of classes and we use a destructor of class, will it clear his position in the vector or we need to erase it ourselves?

class MyClass{
  ...
};

std::vector<MyClass> myClasses(2);
myClasses[0].~MyClass();
gsamaras
  • 71,951
  • 46
  • 188
  • 305
  • 2
    You need to remove it yourself. – orhtej2 Mar 07 '20 at 22:12
  • You should not call the destructor manually. Removing an object from a vector will delete it, so it will be called automatically. If call it yourself, it will end up being called twice, which is not good. – HolyBlackCat Mar 07 '20 at 22:14
  • 1
    There are very, very rare cases when you call the destructor of a class explicitly. This one is not the case! Rule of thumb, you **never** call the destructor explicitly! – user1810087 Mar 07 '20 at 22:17
  • To close-voter: Where is the typo? Or the non-reproducible problem? OP, is a new contributor to the community, please be mindful. :) – gsamaras Mar 07 '20 at 22:25

1 Answers1

4

You should not call the destructor manually. When you call std::vector::erase, the destructor of the object will be called automatically, as @HolyBlackCat commented.

By calling the destructor manually, you'll end up being called twice, which is not good, so remember:

The solution is to never manually call your destructor.

Just call:

myClasses.erase(myClasses.begin() + 0);

which will remove the first object of the vector, resulting in its destructor being called automatically.

gsamaras
  • 71,951
  • 46
  • 188
  • 305