From 6463aab35ccc138cd8abc26f336eec1d254122bd Mon Sep 17 00:00:00 2001 From: neingeist Date: Sun, 13 Apr 2014 10:51:19 +0200 Subject: [PATCH] add a simple example to unique_ptr.cpp --- unique_ptr.cpp | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) 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(); +}