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

前端 未结 11 1046
甜味超标
甜味超标 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:23

    The simple answer is yes - new() creates an object on the heap (with the unfortunate side effect that you have to manage its lifetime (by explicitly calling delete on it), whereas the second form creates an object in the stack in the current scope and that object will be destroyed when it goes out of scope.

提交回复
热议问题