Move value from local stack to heap? (C++)

nonot1 picture nonot1 · Sep 27, 2011 · Viewed 15.3k times · Source

How can I take an object-as-value result from a method call and place it on the heap?

For instance:

The Qt QImage::scaledToWidth method returns a copy of the QImage object.

Right now I'm doing:

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.

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.

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.

Answer

James Kanze picture James Kanze · Sep 27, 2011

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