Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
731 views
Welcome To Ask or Share your Answers For Others

1 Answer

Use 1 when you can, 2 when you have to. The "when you have to" basically translates to "when you're creating an object that whose lifetime is not/cannot be tied to "scope" -- i.e., it must remain in existence after the function that created it exits. You generally want to avoid this if you can though, such as by returning a copy of the object in question, instead of making that object (itself) last after the function returns.

Past that, there are (unfortunately) no really hard and fast guidelines to follow that assure you're doing things as well as possible.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...