什么时候应该使用C ++中的新运算符 [英] when should I use the new operator in C++

查看:149
本文介绍了什么时候应该使用C ++中的新运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个名为 Money 的类,其中包含参数 Dollars Cents

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);


b $ b

我的问题是我应该何时使用(1)和何时使用(2)

My question is when should I use (1) and when should I use (2)

推荐答案

首先在堆栈上创建一个 Money 对象,其生命周期在创建时的范围内。当您点击} 时,意味着超出范围,并返回内存。

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.

第二个创建一个 Money 堆,它的寿命是你想要的,只要你 delete 它。当您希望将对象传递到不同的函数时使用此方法

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

这篇关于什么时候应该使用C ++中的新运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆