I've been using C++ for a short while, and I've been wondering about the new keyword. Simply, should I be using it, or not?
1) With the new keyword...
MyClass* myClass = new MyClass();
myClass->MyField = "Hello world!";
2) Without the new keyword...
MyClass myClass;
myClass.MyField = "Hello world!";
From an implementation perspective, they don't seem that different (but I'm sure they are)... However, my primary language is C#, and of course the 1st method is what I'm used to.
The difficulty seems to be that method 1 is harder to use with the std C++ classes.
Which method should I use?
I recently used the new keyword for heap memory (or free store) for a large array which was going out of scope (i.e. being returned from a function). Where before I was using the stack, which caused half of the elements to be corrupt outside of scope, switching to heap usage ensured that the elements were in tact. Yay!
A friend of mine recently told me there's a simple rule for using the new
keyword; every time you type new
, type delete
.
Foobar *foobar = new Foobar();
delete foobar; // TODO: Move this to the right place.
This helps to prevent memory leaks, as you always have to put the delete somewhere (i.e. when you cut and paste it to either a destructor or otherwise).
Method 1 (using new
)
delete
your object later. (If you don't delete it, you could create a memory leak)delete
it. (i.e. you could return
an object that you created using new
) delete
d; and it should always be deleted, regardless of which control path is taken, or if exceptions are thrown.Method 2 (not using new
)
delete
it later.return
a pointer to an object on the stack)As far as which one to use; you choose the method that works best for you, given the above constraints.
Some easy cases:
delete
, (and the potential to cause memory leaks) you shouldn't use new
.new