lundi 22 octobre 2018

does std::move move object on stack to heap

I have seen code like the following:

//std::stack<T> myStack;
//push items onto stack
std::shared_ptr<T> retVal(std::make_shared<T>(std::move(myStack.top())));
myStack.pop();

Is this really a good idea? The purpose of std::move() is to avoid an expensive copy. If the myStack object is allocated on the stack, Does std::move() or std::make_shared() cause the object to be allocated on the heap? If it does, it seems to defeat the purpose of the std::move().

If however, the myStack object and the item being popped remains on the stack, then the std::shared_ptr seems not quite right. Even though it will probably compile, but the shared_ptr is pointing to something not on the heap, when the shared_ptr destructor is called, it will try to release memory that is on the stack.

Can I please get some help understanding this?

Thank you!

Aucun commentaire:

Enregistrer un commentaire