Alex Rivera | Logout

Why not use pointers for everything in C++?

Asked 2009-06-30T15:26:02.750
78

Suppose that I define some class:

class Pixel {
    public:
      Pixel(){ x=0; y=0;};
      int x;
      int y;
}

Then write some code using it. Why would I do the following?

Pixel p;
p.x = 2;
p.y = 5;

Coming from a Java world I always write:

Pixel* p = new Pixel();
p->x = 2;
p->y = 5;

They basically do the same thing, right? One is on the stack while the other is on the heap, so I'll have to delete it later on. Is there any fundamental difference between the two? Why should I prefer one over the other?

Edit
Report

2 Answers

6

The first case is not always stack allocated. If it's part of an object, it'll be allocated wherever the object is. For example:

class Rectangle {
    Pixel top_left;
    Pixel bottom_right;
}

Rectangle r1; // Pixel is allocated on the stack
Rectangle *r2 = new Rectangle(); // Pixel is allocated on the heap

The main advantages of stack variables are:

  • You can use the RAII pattern to manage objects. As soon as the object goes out of scope, it's destructor is called. Kind of like the "using" pattern in C#, but automatic.
  • There's no possibility of a null reference.
  • You don't need to worry about manually managing the object's memory.
  • It causes fewer memory allocations. Memory allocations, particularly small ones, are likely to be slower in C++ than Java.

Once the object's been created, there's no performance difference between an object allocated on the heap, and one allocated on the stack (or wherever).

However, you can't use any kind of polymorphism unless you're using a pointer - the object has a completely static type, which is determined at compile time.

answered 2009-06-30T15:38:07.470
2

Use pointers and dynamically allocated objects ONLY WHEN YOU MUST. Use statically allocated (global or stack) objects wherever possible.

  • Static objects are faster (no new/delete, no indirection to access them)
  • No object lifetime to worry about
  • Fewer keystrokes More readable
  • Much more robust. Every "->" is a potential access to NIL or invalid memory

To clarify, by 'static' in this context, I mean non-dynamically allocated. IOW, anything NOT on the heap. Yes, they can have object lifetime issues too - in terms of singleton destruction order - but sticking them on the heap doesn't usually solve anything.

answered 2009-06-30T15:35:49.080

Your Answer