when should I use the new operator in C++

后端 未结 9 1978
有刺的猬
有刺的猬 2020-12-21 11:47

Say I have a class called Money which has parameters Dollars and Cents

I could initialize it in the followings 2 ways:

9条回答
  •  粉色の甜心
    2020-12-21 12:27

    In general, you would use form 1 when the object has a limited life span (within the context of a block) and use form 2 when the object must survive the block it is declared in. Let me give a couple of examples:

    int someFunc() {
        Money a(3,15);
        ...
    } // At this point, Money is destroyed and memory is freed.
    

    Alternatively, if you want to have the objects survive the function, you would use new as follows:

    Money *someOtherFunc() {
        Money *a = new Money(3,15);
        ....
        return a;
    } // we have to return a here or delete it before the return or we leak that memory.
    

    Hope this helps.

提交回复
热议问题