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

前端 未结 11 870
甜味超标
甜味超标 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 06:11

    Which method should I use?

    This is almost never determined by your typing preferences but by the context. If you need to keep the object across a few stacks or if it's too heavy for the stack you allocate it on the free store. Also, since you are allocating an object, you are also responsible for releasing the memory. Lookup the delete operator.

    To ease the burden of using free-store management people have invented stuff like auto_ptr and unique_ptr. I strongly recommend you take a look at these. They might even be of help to your typing issues ;-)

提交回复
热议问题