The main difference is where it lives in memory. The "non pointer version" lives on the stack, meaning it will be invalid once the function returns, while the "pointer version" lives on the heap, which means it will be alive and well until somebody calls delete
on it. In general it is considered best practice to put objects on the stack whenever possible, and only on the heap when needed. A good example of needing the object on the heap would be something like this
Obj* f()
{
return new Obj();
}
the new Obj()
creates an Obj
object on the heap and returns a pointer to it, which is then returned from the function.
This, for example, would NOT work
Obj* f()
{
Obj o1;
return &o1; //BAD!!
}
Since the pointer value &o1
references memory on the stack, and f() is cleared off the stack at that point, who knows what will happen. Definitely nothing good.