C++——volatile、const、constexpr、inline、static

volatile 和 const 修饰的变量说明该变量在本程序内不应被修改,但其它程序是可以修改的 volatile 修饰变量,告诉编译器不要优化该变量,每次取值都重新从内存中获取 constexpr 和 inline 修饰的变量,编译器都会进行编译期优化 当对 inline 修饰变量进行取地址操作时,优化会失效 inline 修饰函数相当于 static,只能在当前文件中访问 inline 修饰的变量可以用任意表达式初始化,但这样不保证被优化 inline 其它介绍 static 限制修饰的变量和函数的可见作用域(模块内部),其它的都是副本

September 1, 2022 · 1 min · Rick Cui

C++ 杂记

应用程序内存空间(局部内存堆),程序进程结束时,会被统一都回收释放 公共内存区(全局内存堆)(写设备驱动程序时会使用),使用不当会造成内存泄漏 extern 不能修饰其他模块的静态变量 函数内用 extern 修饰的变量要么来自全局变量,要么来自本身模块的静态变量 extern 只能修饰外部变量(就近原则),不能修饰局部变量 test.cpp: #include <iostream> int etn = 3; // 全局变量 static int s_m; // 模块静态变量 void layout() { std::cout << "test.cpp\tetn=" << etn << std::endl; } another.cpp: static int etn = 4; // 模块静态变量 void myFunc(){ int etn = 5; // 局部自动变量 { extern int etn; int x = etn;// x 是 4 而不是 5 } } charTest....

August 15, 2022 · 2 min · Rick Cui

main 函数执行完后所执行的代码

静态变量在 main 函数前执行初始化 on_exit 注册的函数在 main 执行后再执行 void f(int state, void* msg){ cout << "after main exit.\n"; cout << "state: " << state << "\tmessage: " << (char*)msg << endl; } int main() { cout << "Hello World\n"; on_exit(f, (char*)"this is message"); cout << "end of main.\n"; return 0; } 输出: Hello World end of main. after main exit. state: 0 message: this is message

May 12, 2022 · 1 min · Rick Cui

大端、小端字节序

一、概念 计算机系统中内存是以字节为单位进行编址的,每个地址单元都唯一的对应着 1 个字节(8 bit) 有些类型的长度是超过 1 个字节的,比如 C/C++ 中,short 类型一般是 2 个字节,int 类型一般 4 个字节等。因此这里就存在如何安排多字节数据中,各字节存放顺序的问题。正是因为不同的安排顺序导致了大端存储模式和小端存储模式的存在。 大端模式:是指数据的高字节保存在内存的低地址中,而数据的低字节保存在内存的高地址中(高低低高) 小端模式:是指数据的高字节保存在内存的高地址中,而数据的低字节保存在内存的低地址中(高高低低) 假如有一个 4 字节的数据为 0x12345678(十进制:305419896,0x12 为高字节,0x78 为低字节),若将其存放于地址 0x4000 8000 中,则有: 内存地址 0x4000 8000(低地址) 0x4000 8001 0x4000 8002 0x4000 8003(高地址) 大端模式 0x12 0x34 0x56 0x78 小端模式 0x78 0x56 0x34 0x12 现状:...

April 21, 2022 · 2 min · Rick Cui

const_cast

函数指针和成员函数指针无法用于 const_cast const_cast 使得指向非 const 类型的 const 引用或指针能够被修改 通过 const_cast 修改 const 对象是未定义的行为 struct type { int i; type(): i(3) {} void f(int v) const { // this->i = v; // compile error: this is a pointer to const const_cast<type*>(this)->i = v; // OK as long as the type object isn't const } }; int main() { int i = 3; // i is not declared const const int& rci = i; // const reference const_cast<int&>(rci) = 4; // OK: modifies i std::cout << "i = " << i << '\n'; const int* pci = &i; // *pci = 5; // error: assignment of read-only location ‘* pci’ *const_cast<int*>(pci) = 5; // OK: modifies i std::cout << "i = " << i << '\n'; type t; // if this was const type t, then t....

April 11, 2022 · 2 min · Rick Cui