mercredi 22 avril 2020

Proper Way to Handle Vector of Pointers to Derived Classes?

I don't know how to properly have a vector of derived classes without memory leaks. I tried the following, but it has problems:

#include <iostream>
#include <vector>
using namespace std;

struct base {};

struct derived : public base
{
  derived() {}
};

struct Layer
{
  vector<base*> effects;

  Layer() {}

  ~Layer()
  {
    for(int ii = 0; ii < effects.size(); ii++)
    {
      cout << "called effect deleter" << endl;
      delete effects[ii];
    }
  }
};

int main()
{
  vector<Layer> layers;
  for(int i = 0; i < 10; i++)
  {
    layers.push_back(Layer());
    layers[i].effects.push_back(new derived());
    cout << i << endl;
  }
}

When I compile and run this code, I get the following output:

0
called effect deleter
1
called effect deleter
called effect deleter

I'm confused. Why does it only print 0 and 1 instead of 0 through 9? If I remove the Layer destructor, won't I have a memory leak? What is the proper way to handle this situation?

Aucun commentaire:

Enregistrer un commentaire