when should I use the new operator in C++

后端 未结 9 1917
有刺的猬
有刺的猬 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.

    0 讨论(0)
  • 2020-12-21 12:27

    You should use option two when you want a pointer to an object, and option one when you want a value.

    0 讨论(0)
  • 2020-12-21 12:28

    This is a much more complex question than it looks. The simple answer is

    1) When you want to stack storage and scope bound resource management, when the scope is left the destructor on this object will be called and storage on the stack will be popped.

    Be careful not to pass a pointer to one of these scope-bound objects up the call stack (returning, output parameters), this is an easy way to segfault.

    2) When you want the object allocated on the free-store, this pointer must be deleted or a memory leak will occur.

    Take a look at shared_ptr, scoped_ptr, auto_ptr, et al. for some alternatives that make #2 act in some ways like #1.

    Also, take a look at this question for some pointers on memory management in C++.

    0 讨论(0)
提交回复
热议问题