Skip to content

Instantly share code, notes, and snippets.

@calmofthestorm
Created April 16, 2013 16:43
Show Gist options
  • Save calmofthestorm/5397474 to your computer and use it in GitHub Desktop.
Save calmofthestorm/5397474 to your computer and use it in GitHub Desktop.
Simple example of std::move use with stacks to avoid copies.
#include <stack>
#include <memory>
int main() {
std::stack<std::unique_ptr<int>> A, B;
A.push(std::unique_ptr<int>(new int{1}));
A.push(std::unique_ptr<int>(new int{2}));
A.push(std::unique_ptr<int>(new int{3}));
// Can't do this -- unique_ptrs aren't copyable.
/*
B.push(A.top());
A.pop();
*/
// Can do this.
B.push(std::move(A.top()));
// Now A.top() is in a safe-to-destruct but unspecified state.
// for a unique_ptr that means null. So be careful if that violates
// another object's invariant!
B.pop();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment