garyolsen said:
For a class, MyClass, there are two ways to instantiate an object:
1. MyClass *MC = new MyClass();
2. MyClass MC;
In general, when should you have to use 1 and when 2? What're
advantages/disadvantages of using either?
Thanks!
It seems that beginners (and expatriot Java programmers!) use #1 way too
much. It seems to be associated with the desire to do object oriented
programming. But now you have to manage the memory. If you forget to delete
it you have a memory leak and if you delete it twice you have undefined
behavior.
Another point about #1 is exception safety. For instance:
Fred *p = new Fred();
some_function(p);
delete p;
Looks ok, but if some_function throws, you have a memory leak. For this
reason it is common to use a smart pointer:
#include <memory>
std::auto_ptr<Fred> p(new Fred());
some_function(p.get());
The actual pointer is deleted automatically when p goes out of scope, so you
get no memory leak whether some_function throws or not.
Between smart pointers and standard collection classes, I find very little
reason to use delete or delete [], and I don't miss them a bit.