1 /* 2 * Copyright (C) 2015-2019 Alibaba Group Holding Limited 3 */ 4 5 #include <algorithm> 6 #include <iostream> 7 #include <string.h> 8 9 using namespace std; 10 11 class custom_string { 12 public: custom_string(const char * p)13 custom_string(const char *p) 14 { 15 len = strlen(p); 16 copy_data(p); 17 } 18 custom_string(const custom_string & str)19 custom_string(const custom_string &str) 20 { 21 len = str.len; 22 copy_data(str.strptr); 23 } 24 custom_string(custom_string & str)25 custom_string(custom_string &str) 26 { 27 cout << "rvalue construcotr is called" << endl; 28 if (this != &str) { 29 len = str.len; 30 strptr = str.strptr; 31 str.strptr = NULL; 32 str.len = 0; 33 } 34 } 35 operator =(const custom_string & str)36 custom_string &operator=(const custom_string &str) 37 { 38 if (this != &str) { 39 len = str.len; 40 copy_data(str.strptr); 41 } 42 return *this; 43 } 44 operator =(custom_string && str)45 custom_string &operator=(custom_string &&str) 46 { 47 cout << "rvalue assignment is called" << endl; 48 if (this != &str) { 49 len = str.len; 50 strptr = str.strptr; 51 str.strptr = NULL; 52 str.len = 0; 53 } 54 return *this; 55 } 56 custom_string()57 custom_string() : strptr(NULL), len(0) {} ~custom_string()58 ~custom_string() 59 { 60 if (strptr != NULL) { 61 delete (strptr); 62 } 63 } 64 copycount_clear(void)65 static void copycount_clear(void) { copy_count = 0; }; copycount_get(void)66 static int copycount_get(void) { return copy_count; }; 67 68 private: 69 char * strptr; 70 size_t len; 71 static int copy_count; 72 copy_data(const char * s)73 void copy_data(const char *s) 74 { 75 copy_count++; 76 cout << "copy data, copy count is " << copy_count << endl; 77 strptr = new char[len + 1]; 78 memcpy(strptr, s, len); 79 strptr[len] = '\0'; 80 } 81 }; 82 83 int custom_string::copy_count = 0; 84 rvalue_test(void)85void rvalue_test(void) 86 { 87 int copy_count; 88 89 custom_string::copycount_clear(); 90 91 custom_string a; 92 a = custom_string("ATOS"); 93 94 custom_string b(a); 95 96 copy_count = custom_string::copycount_get(); 97 98 if (copy_count > 2) { 99 cout << "rvalue test error, copy_count is " << copy_count << endl; 100 } else { 101 cout << "rvalue test ok" << endl; 102 } 103 } 104