Today's Lesson (for me): Pointers that mysteriously get deleted!
Posted by Milcho,
31 January 2013
·
292 views
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)
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.
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
Create a custom theme




