Know where your objects live

If you work in an environment where memory management is part of your responsibility then you should be aware of the corner cases in which memory management may come and bite you in the ass. Object ownership is one of those areas.

If you are going to take ownership of an object you need to be very explicit about it. A common (and mostly wrong) pattern is taking ownership of an object, by default. Things work great until you end up with a production coredump after trying to free an invalid pointer.

Foo f1;
Foo *f2 = new Foo;

class BadList {
  Foo *f1, *f2;
  BadList(Foo *f1, Foo *f2) :f1(f1), f2(f2) {}
  ~BadList(){ delete f1; delete f2; }
}

Seen like that it’s more than obvious, but I have seen even experieced programmers fall in this caveat.

Related reading: Oh shit the stack.

Advertisements


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s