What is difference between instantiating an object using new vs. without(使用 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
创建的对象被称为具有动态存储持续时间",并且仅在 delete
d 时被销毁.实际上,这意味着在堆栈上创建和销毁自动变量,而在堆上存储动态对象,但这不是语言所必需的.
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 delete
d. 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 和不使用实例化对象有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 new 和不使用实例化对象有什么区别
基础教程推荐
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01