使用 new 和不使用实例化对象有什么区别 [英] What is difference between instantiating an object using new vs. without

查看:23
本文介绍了使用 new 和不使用实例化对象有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C++ 中,

除了动态内存分配之外,以下两行代码在功能上是否存在差异:

Aside from dynamic memory allocation, is there a functional difference between the following two lines of code:

Time t (12, 0, 0); //t is a Time object

Time* t = new Time(12, 0, 0);//t is a pointer to a dynamically allocated Time object

我当然假设已经定义了一个 Time(int, int, int) ctor.我也意识到在第二种情况下 t 需要删除,因为它是在堆上分配的.还有其他区别吗?

I am assuming of course that a Time(int, int, int) ctor has been defined. I also realize that in the second case t will need to be deleted as it was allocated on the heap. Is there any other difference?

推荐答案

行:

Time t (12, 0, 0);

...在局部作用域中分配一个Time类型的变量,一般在栈上,当它的作用域结束时会被销毁.

... allocates a variable of type Time in local scope, generally on the stack, which will be destroyed when its scope ends.

相比之下:

Time* t = new Time(12, 0, 0);

... 通过调用 ::operator new()Time::operator new() 分配一块内存,然后调用 Time::Time()this 设置为该内存块内的一个地址(也作为 new 的结果返回),然后将其存储在 <代码>t.如您所知,这通常在堆上完成(默认情况下)并且要求您稍后在程序中delete它,而t中的指针代码>通常存储在堆栈中.

... allocates a block of memory by calling either ::operator new() or Time::operator new(), and subsequently calls Time::Time() with this set to an address within that memory block (and also returned as the result of new), which is then stored in t. As you know, this is generally done on the heap (by default) and requires that you delete it later in the program, while the pointer in t is generally stored on the stack.

注意:我在这里使用的一般是指常见的实现.C++ 标准不区分堆栈和堆作为机器的一部分,而是根据它们的生命周期来区分.局部范围内的变量被称为具有自动存储持续时间",并因此在本地范围结束时被销毁;并且使用 new 创建的对象被称为具有动态存储持续时间",并且仅在 deleted 时被销毁.实际上,这意味着在堆栈上创建和销毁自动变量,而在堆上存储动态对象,但这不是语言所必需的.

N.B.: My use of generally here is speaking in terms of common implementations. The C++ standard does not distinguish stack and heap as a part of the machine, but rather in terms of their lifetime. Variables in local scope are said to have "automatic storage duration," and are thus destroyed at the end of local scope; and objects created with new are said to have "dynamic storage duration," and are destroyed only when deleted. In practical terms, this means that automatic variables are created and destroyed on the stack, and dynamic objects are stored on the heap, but this is not required by the language.

这篇关于使用 new 和不使用实例化对象有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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