💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
# 指针 引用 ~~~ int *ip; /* 一个整型的指针 */ double *dp; /* 一个 double 型的指针 */ float *fp; /* 一个浮点型的指针 */ char *ch; /* 一个字符型的指针 */ int& r = i; double& s = d; const string &str = "string" //const类型引用可以引用右值 //函数指针 void (*fun)(int, int) //类函数指针 //静态成员函数指针 void (*funStatic)() = &ClassName::staticFun; //成员方法函数指针 void (ClassName::*funNoStatic)() = &ClassName::noStaticFun; //使用 funStatic(); (obj->*funNoStatic)(); ~~~ # 二级指针 ``` int a = 10; int *ptr1 = &a; int **ptr = &ptr1; ``` # 右值引用 ``` 不可以取地址的变量是右值 int &&a = 10; int &&a = fun1(); int a = 10; int &&b = std::move(10) ``` # 移动语义 **要让你设计的对象支持移动的话,通常需要下面几步:** 1. 你的对象应该有分开的拷贝构造和移动构造函数(除非你只打算支持移动,不支持拷贝——如 unique\_ptr)。 2. 你的对象应该有 swap 成员函数,支持和另外一个对象快速交换成员。 3. 在你的对象的名空间下,应当有一个全局的 swap 函数,调用成员函数 swap 来实现交换。支持这种用法会方便别人(包括你自己在将来)在其他对象里包含你的对象,并快速实现它们的 swap 函数。 4. 实现通用的 operator=。 5. 上面各个函数如果不抛异常的话,应当标为 noexcept。这对移动构造函数尤为重要 ``` #include <iostream> // std::cout/endl #include <utility> // std::move using namespace std; class Obj { public: Obj() { cout << "Obj()" << endl; } Obj(const Obj&) { cout << "Obj(const Obj&)" << endl; } Obj(Obj&&) { cout << "Obj(Obj&&)" << endl; } }; Obj simple() { Obj obj; // 简单返回对象;一般有 NRVO return obj; } Obj simple_with_move() { Obj obj; // move 会禁止 NRVO return std::move(obj); } Obj complicated(int n) { Obj obj1; Obj obj2; // 有分支,一般无 NRVO if (n % 2 == 0) { return obj1; } else { return obj2; } } int main() { cout << "*** 1 ***" << endl; auto obj1 = simple(); cout << "*** 2 ***" << endl; auto obj2 = simple_with_move(); cout << "*** 3 ***" << endl; auto obj3 = complicated(42); } ``` # const 引用 ``` const int &a = 10 const int &a = b const引用既能引用左值 也能引用右值 ```