将值从本地堆栈移到堆? (C ++) [英] Move value from local stack to heap? (C++)
问题描述
如何从方法调用中获取对象即值"结果并将其放置在堆中?
How can I take an object-as-value result from a method call and place it on the heap?
例如:
Qt QImage::scaledToWidth
方法返回QImage
对象.
现在我正在做
QImage *new_img_on_heap = new QImage(old_imgage_on_heap->scaledToWidth(2000));
这是唯一的方法吗?似乎当我已经在堆栈上拥有一个完美的好对象时,就很难制作一个第三个全新对象.
Is this the only way? Seems like it's going through the trouble of making a 3rd whole new object when I already have a perfect good one on the stack.
我想将其放在堆上的原因是因为实际的QImage
很大,并且我希望它比当前方法的生存期更长.我打算在班级的某个字段中塞满指向它的指针.
The reason I want to put it on the heap is because the real QImage
is large, and I want it to outlive the lifetime of the current method. I was intending to stuff a pointer to it in a field of my class.
我知道QImage
具有某种隐式数据共享,但是我不清楚它是如何在后台运行的.另外,我想知道一个通用的解决方案,是否需要使用设计不如Qt的对象.
I know that QImage
has some sort of implicit data sharing, but I'm not exactly clear on how it works under the hood. Plus, I wanted to know a general solution should I ever need to use objects not as well designed as Qt's.
推荐答案
对象由其地址标识.如果你想在另一个地方 地址,您必须构建一个新的地址;你不能移动物体. (甚至 在C ++ 11中,新的移动"语义实际上并没有移动 目的;如果您知道的话,他们提供了一种优化的方式来转移其价值 这样您就不需要从其移动的位置来获取该值了.)
An object is identified by its address. If you want it at another address, you have to construct a new one; you can't move objects. (Even with C++11, the new “move” semantics don't actually move an object; they provide an optimized way of moving its value, if you know that you won't need the value from where you're moving it.)
这篇关于将值从本地堆栈移到堆? (C ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!