|
| 1 | +// Copyright (c) 2020 by Chrono |
| 2 | +// |
| 3 | +// g++ test08.cpp -std=c++11 -o a.out;./a.out |
| 4 | +// g++ test08.cpp -std=c++14 -o a.out;./a.out |
| 5 | +// g++ test08.cpp -std=c++14 -I../common -o a.out;./a.out |
| 6 | + |
| 7 | +#include <cassert> |
| 8 | + |
| 9 | +#include <iostream> |
| 10 | +#include <memory> |
| 11 | +#include <string> |
| 12 | + |
| 13 | +template<class T, class... Args> |
| 14 | +std::unique_ptr<T> |
| 15 | +my_make_unique(Args&&... args) |
| 16 | +{ |
| 17 | + return std::unique_ptr<T>( |
| 18 | + new T(std::forward<Args>(args)...)); |
| 19 | +} |
| 20 | + |
| 21 | +void case1() |
| 22 | +{ |
| 23 | + using namespace std; |
| 24 | + |
| 25 | + unique_ptr<int> ptr1(new int(10)); |
| 26 | + assert(*ptr1 = 10); |
| 27 | + assert(ptr1 != nullptr); |
| 28 | + |
| 29 | + unique_ptr<string> ptr2(new string("hello")); |
| 30 | + assert(*ptr2 == "hello"); |
| 31 | + assert(ptr2->size() == 5); |
| 32 | + |
| 33 | + //ptr1++; |
| 34 | + //ptr2 += 2; |
| 35 | + |
| 36 | + //unique_ptr<int> ptr3; |
| 37 | + //*ptr3 = 42; |
| 38 | + |
| 39 | + auto ptr3 = make_unique<int>(42); |
| 40 | + assert(ptr3 && *ptr3 == 42); |
| 41 | + |
| 42 | + auto ptr4 = make_unique<string>("god of war"); |
| 43 | + assert(!ptr4->empty()); |
| 44 | + |
| 45 | + auto ptr5 = my_make_unique<long>(100L); |
| 46 | + assert(*ptr5 == 100); |
| 47 | +} |
| 48 | + |
| 49 | +void case2() |
| 50 | +{ |
| 51 | + using namespace std; |
| 52 | + |
| 53 | + auto ptr1 = make_unique<int>(42); |
| 54 | + assert(ptr1 && *ptr1 == 42); |
| 55 | + |
| 56 | + auto ptr2 = std::move(ptr1); |
| 57 | + assert(!ptr1 && ptr2); |
| 58 | +} |
| 59 | + |
| 60 | +void case3() |
| 61 | +{ |
| 62 | + using namespace std; |
| 63 | + |
| 64 | + auto ptr1 = make_shared<int>(42); |
| 65 | + assert(ptr1 && *ptr1 == 42); |
| 66 | + |
| 67 | + auto ptr2 = make_shared<string>("god of war"); |
| 68 | + assert(!ptr2->empty()); |
| 69 | +} |
| 70 | + |
| 71 | +int main() |
| 72 | +{ |
| 73 | + using namespace std; |
| 74 | + |
| 75 | + case1(); |
| 76 | + case2(); |
| 77 | + case3(); |
| 78 | + |
| 79 | + cout << "smart_ptr demo" << endl; |
| 80 | +} |
0 commit comments