开发者

newb c++ question: when to use "new"? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicat开发者_StackOverflow中文版e:

when should I use the new operator in C++

say i have a class called Money which has parameters dollars and cents

i could initialize it in the followings 2 ways

1) Money a(3,15);

2) Money *b=new Money(3,15);

my question is when should i use 1) and when should i use 2)


1) creates a local object a of type Money, which is allocated on the stack. a will be destroyed when it goes out of scope, e. g. when the function that created it exits.

2) dynamically allocates an object of type Money on the heap. That object will persist even after the function that created it exits, until delete is called on it.

If you only need an object to use within a function, it is generally ok to use 1). If you need the object to persist after your function exits, use 2). You should also use 2) if the object is very large, i. e. if it takes up a lot of memory. If you use 2), remember to call delete when you no longer need the object.

There is more to it, such as the use of polymorphism, but this should get you started.


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

credit: https://stackoverflow.com/users/369503/yoel

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜