diff --git a/unique_ptr.cpp b/unique_ptr.cpp index 4fcb86e..2e79e90 100644 --- a/unique_ptr.cpp +++ b/unique_ptr.cpp @@ -3,12 +3,26 @@ #include #include -int main(void) { +void simple() { + // From Wikipedia. + + std::unique_ptr p1(new int(5)); + + // Compile error - can't copy p1! + // std::unique_ptr p2 = p1; + + assert(p1 != NULL); + // Transfers ownership. p3 now owns the memory and p1 is rendered invalid: + std::unique_ptr p3 = std::move(p1); + assert(p1 == NULL && p3 != NULL); +} + +void container() { std::vector> v; std::unique_ptr q(new int(42)); assert(q != NULL); - // v.push_back(q); + // v.push_back(q); <- Compile error v.push_back(std::move(q)); assert(q == NULL); @@ -16,3 +30,8 @@ int main(void) { std::cout << *e << std::endl; } } + +int main(void) { + simple(); + container(); +}