Created
April 16, 2013 16:43
-
-
Save calmofthestorm/5397474 to your computer and use it in GitHub Desktop.
Simple example of std::move use with stacks to avoid copies.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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