Friday 22 July 2016

pointers - When should I use the new keyword in C++?



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?



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 in tact. 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).



Answer



Method 1 (using new)




  • Allocates memory for the object on the free store (This is frequently the same thing as the heap)

  • Requires you to explicitly delete your object later. (If you don't delete it, you could create a memory leak)

  • Memory stays allocated until you delete it. (i.e. you could return an object that you created using new)

  • The example in the question will leak memory unless the pointer is deleted; and it should always be deleted, regardless of which control path is taken, or if exceptions are thrown.




Method 2 (not using new)




  • Allocates memory for the object on the stack (where all local variables go) There is generally less memory available for the stack; if you allocate too many objects, you risk .

  • You won't need to delete it later.

  • Memory is no longer allocated when it goes out of scope. (i.e. you shouldn't 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:




  • If you don't want to worry about calling delete, (and the potential to cause memory leaks) you shouldn't use new.

  • If you'd like to return a pointer to your object from a function, you must use new


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...