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

Categories

0 votes
765 views
in Technique[技术] by (71.8m points)

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)

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...