使用new和without实例化对象之间的区别 [英] What is difference between instantiating an object using new vs. without

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

问题描述

在C ++中,



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

 时间t(12,0,0); // t是一个时间对象

时间* t = new Time(12,0,0); // t是指向动态分配的Time对象的指针

我假设已经定义了一个Time(int,int,int)ctor。我也意识到,在第二种情况下,t将需要被删除,因为它是在堆上分配。是否有其他差异?

解决方案

行:

 时间t(12,0,0); 

...分配类型的变量

相比之下:

pre> 时间* t =新时间(12,0,0);

...通过调用 :: operator new ()或 Time :: operator new(),然后调用 Time :: Time()设置为该内存块中的地址(也作为 new 的结果返回)然后存储在 t 中。如你所知,这通常在堆上完成(默认情况下),并要求你稍后在程序中 delete ,而 t 通常存储在堆栈中。


In 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

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?

解决方案

The line:

Time t (12, 0, 0);

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

By contrast:

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

... 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.

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

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