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

前端 未结 11 974
甜味超标
甜味超标 2020-11-22 05:47

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 keywo

11条回答
  •  一整个雨季
    2020-11-22 06:14

    The second method creates the instance on the stack, along with such things as something declared int and the list of parameters that are passed into the function.

    The first method makes room for a pointer on the stack, which you've set to the location in memory where a new MyClass has been allocated on the heap - or free store.

    The first method also requires that you delete what you create with new, whereas in the second method, the class is automatically destructed and freed when it falls out of scope (the next closing brace, usually).

提交回复
热议问题