1. 程式人生 > 實用技巧 >C++基礎類

C++基礎類

  1. 預設構造,析構
  2. 拷貝構造,移動構造
  3. 拷貝賦值,移動賦值
  4. 取值
  5. 右值引用
// g++ testClass.cc -g -std=c++11 && ./a.out
#include <iostream>
#include <string.h>
using namespace std;

class MyStr
{
private:
    char *name = NULL;
    int id;
    inline void MyStrncpy(char *dst, const char *src, size_t len) {
        if
(dst != src) { strncpy(dst, src, len); dst[len] = '\0'; } } inline void Reset() { id = 0; if (name) { delete[] name; name = NULL; } } inline void Clear() { id = 0; name = NULL; } inline
void DeepCopy(const MyStr &other) { id = other.id; name = new char[strlen(other.name) + 1]; MyStrncpy(name, other.name, strlen(other.name)); } inline void ShallowCopy(const MyStr &other) { id = other.id; name = other.name; } public
: // 預設建構函式 MyStr():id(0),name(NULL) { cout << "構造: " << __func__ << endl; } // 建構函式 MyStr(int _id, char *_name) { cout << "普通構造: " << __func__ << endl; id = _id; name = new char[strlen(_name) + 1]; MyStrncpy(name, _name, strlen(_name)); } // 解構函式 ~MyStr() { cout << "析構: " << __func__ << endl; Reset(); } // 拷貝構造 MyStr(const MyStr& other) { cout << "拷貝構造: " << __func__ << endl; DeepCopy(other); } // 移動構造 MyStr(MyStr &&other) { cout << "移動構造: " << __func__ << endl; ShallowCopy(other); other.Clear(); } // 拷貝賦值, rhs means right hand side value MyStr &operator=(const MyStr &rhs) { cout << "拷貝賦值: " << __func__ << endl; if (this != &rhs) { Reset(); DeepCopy(rhs); } return *this; } // 移動賦值 MyStr &operator=(MyStr &&rhs) { cout << "移動賦值: " << __func__ << endl; if (this != &rhs) { Reset(); ShallowCopy(rhs); rhs.Clear(); } return *this; } }; int main() { cout << "普通構造====================" << endl; MyStr str1(1, (char*)"aaa"); cout << "普通構造====================" << endl; MyStr str2(2, (char*)"bbbb"); cout << "拷貝賦值====================" << endl; str2 = str1; cout << "拷貝構造====================" << endl; MyStr str3 = str2; cout << "拷貝構造====================" << endl; MyStr str4(str2); cout << "移動構造====================" << endl; MyStr str5(std::move(str2)); cout << "移動構造====================" << endl; MyStr str6 = std::move(str5); cout << "普通構造====================" << endl; MyStr str7(3, (char*)"ccccc"); cout << "移動賦值====================" << endl; str7 = std::move(str6); return 0; }
View Code