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