jeudi 15 juillet 2021

Vector element Destructor not called with reserve

I have this class:

class aa
{
public:
  int i = 0;    
  ~aa(){
  std::cout << "killin in the name of" << std::endl;
    }
};

And I want to make a vector of this class. First I thought o reserving the needed size:

int main()
{
    std::vector<aa> vec;
    vec.reserve(2);
    vec[0] = *(new aa());
    vec[1] = *(new aa());
    //use the vector
    
    vec.clear();

    return 0;
}

But the destructor was not called. On the other side, when I fill the Vector using push_back

int main()
{
    std::vector<aa> vec;
    vec.push_back(*(new aa()));
    vec.push_back(*(new aa()));
    //use the vector
    
    vec.clear();

   return 0;
}

I actually get the destructor called.

Why?

Aucun commentaire:

Enregistrer un commentaire