0

I am getting a seg fault when trying to add a pointer to an object to a vector in an instance of another object. I am adding multiple pointers to the vector at once and the first one works but the second attempt keeps tossing seg faults.

class Observer {
  Observer();
  observe();
};

class Subject {
  std::vector<Observer*> *observers;
  std::string name;

  Subject();
  virtual std::string getName();
  virtual void addObserver(Observer *observer) {
    observers->push_back(observer);
  }
};

class Base : public Subject {
  Base(std::string newName) { name = newName; }
};

class Derivative : public Subject, public Observer {
  float a;
  float b;
  float c;
  Derivative(a, b, c) { this->a = a; this->b = b; this->c = c; }

};

class Board : public Base {
   Base *base;

   Board(std::string newName, Base *newBase) { name = newName; base = newBase; }

   void initializeDerivatives(int start, int end) {
     for (int i = start; i <= end; ++i) {
       addObserver(new Derivative(start, start + 1, start + 2)); //works
       base->addObserver(new Derivative(start, start + 1, start + 2)); //THIS WORKS
       addObserver(new Derivative(start, start + 2, start + 3)); //works
       base->addObserver(new Derivative(start, start + 2, start + 3)); //seg fault here
     }
   }
};

int main() {
  Base myBase("MYBASE");
  Board myBoard("MYBASE", myBase);

  myBoard.initializeDerivatives(1, 10);
}

I was getting seg faults earlier when I declared myBoard and myBase as pointers: Base* myBase = new Base("MYBASE"); Board* myBoard = new Board("MYBASE", myBase);

And I was unsure why that was since I thought using the new operator would actually initialize the instance of the object. Changing it to make the actual objects still allows me to add one pointer to the observers vector, but the second one isn't working. Any thoughts?

4

1 回答 1

1

class Subject,你应该改变这个:

std::vector<Observer*> *observers;

对此:

std::vector<Observer*> observers;

作为指针,您的代码不会显示该指针在任何地方被初始化。如果它在构造函数初始化,则可能存在内存泄漏,因为Subject没有析构函数。

于 2013-03-18T18:41:16.523 回答