/* attempt to deal with prototype, bootstrap, jquery conflicts */ /* for dropdown menus */

Jump to content

February 2017 »

1920 21 22232425

Recent Comments

- - - - -

Today's Lesson (for me): Pointers that mysteriously get deleted!

4: Adsense

I'm posting this as an excercise/lesson, hopefully its useful to someone.
Eight years after I started learning c++, I was still caught off guard by this.

Basically I had code like this: (ignore the LOG_DEBUG - that was just put there when I was testing this)
struct ViewMember
  ViewMember(Widget *wid, int wei) : widget(wid), weight(wei) { }
  ~ViewMember() { LOG_DEBUG << "calling View Member destructor"; delete widget; }
  Widget *widget;
  int weight;
now, in a class called View, I have a member - widgetList is of type std::vector<ViewMember>
View& View::AddWidget (Widget *toAdd, int weight)
  if (weight < 1)
    weight = 1;
  if (Contains(toAdd))
    return (*this); // won't add same widget again
  widgetList.push_back(ViewMember(toAdd, weight));
  needToReorganize = true;
  return (*this);
This code (barring typos I may have made in copy/re-arrange) compiles fine, without warnings or errors.

However, once I actually tried to access something in widgetList, I got a crash - it turns out my widgetList[i].widget was an invalid pointer... as if something had deleted it.

I went through this, and I've figured it out, but I thought I'd share since I think it's somewhat important/interesting.

The Problem

The Solution

Note: GameDev.net moderates comments.