C++基础类知识
- 默认构造,析构
- 拷贝构造,移动构造
- 拷贝赋值,移动赋值
- 取值
- 右值引用
- 其它
- 基类的析构函数应使用virtual 关键字,保证子类的析构函数能够被正常调用
- 作为接口类,如果不是基类,应该用final关键字
1 // g++ testClass.cc -g -std=c++11 && ./a.out 2 #include <iostream> 3 #include <string.h> 4 using namespace std; 5 6 class MyStr final 7 { 8 private: 9 char *name = NULL; 10 int id; 11 inline void MyStrncpy(char *dst, const char *src, size_t len) { 12 if (dst != src) { 13 strncpy(dst, src, len); 14 dst[len] = '\0'; 15 } 16 } 17 inline void Reset() { 18 id = 0; 19 if (name) { 20 delete[] name; 21 name = NULL; 22 } 23 } 24 inline void Clear() { 25 id = 0; 26 name = NULL; 27 } 28 inline void DeepCopy(const MyStr &other) { 29 id = other.id; 30 name = new char[strlen(other.name) + 1]; 31 MyStrncpy(name, other.name, strlen(other.name)); 32 } 33 inline void ShallowCopy(const MyStr &other) { 34 id = other.id; 35 name = other.name; 36 } 37 public: 38 // 默认构造函数 39 explicit MyStr():id(0),name(NULL) { 40 cout << "构造: " << __func__ << endl; 41 } 42 // 构造函数 43 explicit MyStr(int _id, char *_name) { 44 cout << "普通构造: " << __func__ << endl; 45 id = _id; 46 name = new char[strlen(_name) + 1]; 47 MyStrncpy(name, _name, strlen(_name)); 48 } 49 // 析构函数 50 ~MyStr() { 51 cout << "析构: " << __func__ << endl; 52 Reset(); 53 } 54 // 拷贝构造 55 MyStr(const MyStr& other) { 56 cout << "拷贝构造: " << __func__ << endl; 57 DeepCopy(other); 58 } 59 // 移动构造 60 MyStr(MyStr &&other) { 61 cout << "移动构造: " << __func__ << endl; 62 ShallowCopy(other); 63 other.Clear(); 64 } 65 // 拷贝赋值, rhs means right hand side value 66 MyStr &operator=(const MyStr &rhs) { 67 cout << "拷贝赋值: " << __func__ << endl; 68 if (this != &rhs) { 69 Reset(); 70 DeepCopy(rhs); 71 } 72 return *this; 73 } 74 // 移动赋值 75 MyStr &operator=(MyStr &&rhs) { 76 cout << "移动赋值: " << __func__ << endl; 77 if (this != &rhs) { 78 Reset(); 79 ShallowCopy(rhs); 80 rhs.Clear(); 81 } 82 return *this; 83 } 84 }; 85 86 int main() 87 { 88 cout << "普通构造====================" << endl; 89 MyStr str1(1, (char*)"aaa"); 90 cout << "普通构造====================" << endl; 91 MyStr str2(2, (char*)"bbbb"); 92 cout << "拷贝赋值====================" << endl; 93 str2 = str1; 94 cout << "拷贝构造====================" << endl; 95 MyStr str3 = str2; 96 cout << "拷贝构造====================" << endl; 97 MyStr str4(str2); 98 cout << "移动构造====================" << endl; 99 MyStr str5(std::move(str2)); 100 cout << "移动构造====================" << endl; 101 MyStr str6 = std::move(str5); 102 cout << "普通构造====================" << endl; 103 MyStr str7(3, (char*)"ccccc"); 104 cout << "移动赋值====================" << endl; 105 str7 = std::move(str6); 106 return 0; 107 }