基本概念

  • 指针相关
    • 悬挂引用
      • 指针内容指向了被释放了的内容
      • 有趣的例子
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <string>
#include <windows.h>

using namespace std;

int* ptr = NULL;

void fun() {
int i = 10;
ptr = &i;
}

int main(void) {

fun();
cout << "*ptr= " << *ptr << endl;
Sleep(100);
cout << "一秒钟后,fun()中的i变量的存储空间被释放, ptr所指对象的值为:" << endl;
cout << " *ptr = " << *ptr << endl;

printf("\n");
system("pause");
return 0;
}

  • 野指针

    • 未被初始化的指针
  • 内存泄漏

    • 内存未被释放,而指针失去这片内存区的地址
  • C++语法相关相关

    • C++20得到右值,会执行隐式的移动语义
      • C++17则不会
    • -fsanitize=address 用于编译检查内存访问错误
    • C++20 支持auto返回,不借助decltype进行后置类型指定
    • 检查是否是引用类型requires std::is_rvalue_reference_v|| requires std::is_rvalue_reference_v
    • std::same_as<std::remove_cvref_t<T1>, std::remove_cvref_t<T1> >
    • 其中,std::same_as判断两种类型是否相同
    • 其中,std::remove_cvref_t 移除csv限定符,返回引用
    • LINE 用于输出当前文件的行号
    • std::commt_type_t返回共同的基类

代码实例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <iostream>
#include <string>
#include <type_traits>
#include <concepts>

struct MyString: public std::string {
using std::string::string;
MyString(const MyString& s) : std::string(s) {
std::cout << "in copy for: " << *this <<std::endl;
}
MyString(MyString&& s) noexcept : std::string(std::move(s)) {
std::cout << "in move for:" << *this <<std::endl;
}
}


template<class T1, class T2>
struct return_type {
using type = const std::common_type_t<std::remove_cvref_t<T1>, std::remove_cvref_t<T2>>;
}

template<class T1, class T2>
requires std::is_lvalue_reference_v<T1> &&
std::is_lvalue_reference_v<T2> &&
std::same_as<std::remove_cvref_t<T1>, std::remove_cvref_t<T2>>
struct return_type<T1, T2> {
using type = const std::common_type_t<std::remove_cvref_t<T1>, std::remove_cvref_t<T2>>;
}

template<class T1, class T2>
using return_type_t = return_type<T1, T2>::type;

template<class T1, class T2>
return_type_t<T1, T2> my_max(T1&& a, T2&& b)
{
if (a < b)
return b;
return a;
}

int main() {

MyString a = "hello";
const MyString b = "world";
const MyString& res = my_max(a, b);



return 0;
}