Open v4if opened 7 years ago
当所指向的对象被释放或者收回,但是对该指针没有作任何的修改,以至于该指针仍旧指向已经回收的内存地址,此情况下该指针便称悬垂指针(也叫迷途指针)。
某些编程语言允许未初始化的指针的存在,而这类指针即为野指针。
new int[] 是创建一个int型数组,数组大小是在[]中指定,例如: int * p = new int[3]; //申请一个动态整型数组,数组的长度为[]中的值
new int()是创建一个int型数,并且用()括号中的数据进行初始化,例如: int *p = new int(10); // p指向一个值为10的int数。
int *next = new int[patt.length() + 1];
sizeof()与strlen()的区别,strlen()不计算'\0'
// 1-(size_t)2 无符号 正最大
// 易产生bug
for (int j = i; j < s.length() - len; j = j + len) {}
for (int j = i; j + len < s.length(); j = j + len) {}
// 容易导致缓冲区溢出的字符串处理函数
char * gets ( char * str );
char * strcat ( char * destination, const char * source );
char * strcpy ( char * destination, const char * source );
int sprintf ( char * str, const char * format, ... );
// 替代函数
char * fgets ( char * str, int num, FILE * stream );
char * strncat ( char * destination, const char * source, size_t num );
char * strncpy ( char * destination, const char * source, size_t num );
int snprintf ( char * s, size_t n, const char * format, ... );
snprintf(buff, sizeof(buff), "%s\r\n", ctime(&ticks));
AddressSanitizer 检查内存越界访问和使用已释放的内存等问题
To compile: g++ -O -g -fsanitize=address use-after-free.c
一些容易误解的函数
// 参数是秒
unsigned int sleep(unsigned int seconds);
// 第二个参数是子串长度!而非终结字符
string substr (size_t pos = 0, size_t len = npos) const;
std::thread my_thread(background_task());
这里相当于声明了一个名为my_thread的函数,这个函数带有一个参数(函数指针指向没有参数并返回background_task对象的函数),返回一个std::thread对象的函数,而非启动了一个线程
// 使用多组括号
std::thread my_thread((background_task()));
// 或使用新统一的初始化语法
std::thread my_thread{background_task()};
// 使用lambda表达式,允许使用一个可以捕获局部变量的局部函数
std::thread my_thread([]{
do_something();
});
如std::map<>,这里列出了三个常见关联容器的方式:
assert() 编写代码时,我们总是会做出一些假设,断言就是用于在代码中捕捉这些假设,可以将断言看作是异常处理的一种高级形式。断言表示为一些布尔表达式,程序员相信在程序中的某个特定点该表达式值为真
如果你的类可以被non-trivial继承,就该有个virtual destructor。这样做是为了当用一个基类的指针删除一个派生类的对象时,派生类的析构函数会被调用。 并不是要把所有类的析构函数都写成虚函数。因为当类里面有虚函数的时候,编译器会给类添加一个虚函数表,里面来存放虚函数指针,这样就会增加类的存储空间。所以,只有当一个类被用来作为基类的时候,才把析构函数写成虚函数。
覆写、隐藏与重载的区别
const
const used with functions
Compiler Generated Functions
Disallow Functions
Virtual Destructor and Smart Destructor
All classes in STL have no virtual destructor, so be careful inheriting from them.
Exceptions in Destructors
Henry is born. Bob is born. Bob is destroyed. Henry is destroyed. 20 is caught.
Virtual Function [dynamic binding]
Should avoid calling virtual function in a constructor or destructor.
Handling Self-Assignment
Resource Acquisition Initialization
Strcut Vs Class
Resource Managing Class
Virtual Constructor - Clone() Function
Type Conversion
Inheritance - Public, Protected, and Private
Understanding rvalue and lvalue
Dynamic Polymorphism
Static Polymorphism
Multiple Inheritance
Namespace and Keyword "using"