C ++对象创建和内存分配 [英] C++ Object Creation and Memory Allocation

查看:326
本文介绍了C ++对象创建和内存分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我有一个简单的Movie对象,该对象仅跟踪一些数据成员的名称,长度和成本.

Let's say I have a simple Movie object that just keeps track of a few data members of name, length and cost.

如果在我的驱动程序文件中,我将创建一个Movie对象.首选和:

If in my driver file, I create a Movie object. Which is preferred and the difference of :

Movie firstMovie = Movie("Titanic", 126, 13.2);

Movie* firstMovie = new Movie("Titanic", 126, 13.2);

我认为后者是如果要执行该对象中的方法时是否需要访问该对象.换句话说,如果创建的第一个对象像在方法中那样被初始化,则一旦该方法执行完毕,由于未为其分配内存,我们将失去任何连接.我的思维方式正确吗?这不是家庭作业,更多的是我从Java过渡以来一直潜伏的问题.谢谢.

I would think that the latter is if we were to have the need to access this object if the method it was in were to be done executed. In other words, if the first object created was initialized like that in a method, then once the method is done executing, we would lose any connection since memory was not allocated for it. Is my way of thinking correct? This is not homework, more of a question that's been lurking since my transition from Java. Thank you.

推荐答案

我认为您了解两者之间的区别.相反,问题是我应该选择哪个?"就个人而言,如果我能摆脱它,我宁愿将东西放到堆栈上.如今,您的堆栈足够大,除非有其他错误,否则堆栈不会溢出,并且将内容放到堆栈上意味着(1)无需手动delete;(2)更有可能位于内存缓存中的内存要比堆上的东西多,并且(3)分配内存的速度要尽可能快.

I think you understand the difference between the two fine. Instead, the question is "which should I prefer?" Personally, if I can get away with it, I prefer to put things on the stack. Nowadays your stack is large enough that you won't get a stack overflow unless you have some other bug, and putting things on the stack means (1) there's no need to delete it by hand, (2) it's more likely to be in the memory cache than stuff on the heap, and (3) allocating the memory is as fast as you can get.

但是,有时候您无法摆脱它.在这种情况下,请继续进行操作并将其放到堆上.

However, there are times that you can't get away with it. In those cases, go ahead and put things on the heap.

这种困惑来自戈斯林奇怪地坚持使用new来表示让我成为一个物体". Java文档总是吹牛说您不需要delete对您进行new编辑的事情(由于垃圾收集器),但是似乎从来没有提到在C ++中您不必进行new事情几乎和Java一样多.

The confusion comes from Gosling's strange insistence on using new to mean "make me an object." Java documentation always brags about how you don't need to delete things that you new-ed up (because of the garbage collector) but never seems to mention that in C++ you don't have to new things up nearly as often as in Java.

这篇关于C ++对象创建和内存分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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