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?
- With the
newkeyword…
MyClass* myClass = new MyClass(); myClass->MyField = "Hello world!";
- Without the
newkeyword…
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?
Update 1:
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 intact. Yay!
Update 2:
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)deleteyour object later. (If you don’t delete it, you could create a memory leak)deleteit. (i.e. you couldreturnan object that you created usingnew)deleted; and it should always be deleted, regardless of which control path is taken, or if exceptions are thrown.Method 2 (not using
new)deleteit later.returna 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 usenew.new