Test test;
will create an object on the stack. It's local to the function main
, and will be automatically de-allocated when main
exits. Use this when you only need to use an object in the current block.
Test *pointer = new Test();
will create an object on the heap, with a lifetime that isn't limited to the block in which it is declared. When you declare an object this way - using new
- then at some point you'll need to call delete
on the object or you'll leak memory, so you assume the additional burden of handling the memory management. Use this when you need to create an object that needs to stick around, i.e. in other parts of your code, past the current function.
Given these points, the following code has a problem:
Test *pointer = new Test();
Test test;
pointer = &test;
When you assign to pointer
the reference to test
, you lose the pointer to the object that you've allocated, and leaked memory. Furthermore, if you do this in a context where you might use pointer
elsewhere, e.g. in a function that returns a reference to a Test
object, it will point to a memory address that isn't valid after the function exits.