c++pointersreferencenew-operatorkeyword

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!";
  1. 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 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).


Solution

  • Method 1 (using new)

    Method 2 (not using new)

    As far as which one to use; you choose the method that works best for you, given the above constraints.

    Some easy cases: