when should I use the new operator in C++

后端 未结 9 2013
有刺的猬
有刺的猬 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:09

    The first one creates a Money object on the stack, its lifespan is within the scope of when it was created. Meaning when you hit a } it goes out of scope and the memory is returned. Use this when you want to create an object within one function.

    The second one creates a Money object on the heap, its lifespan is as long as you want it to be, namely until you delete it. Use this when you want your object to be passed around to different functions

提交回复
热议问题