内存区/类型cast/static@C++
2022/3/10 7:14:46
本文主要是介绍内存区/类型cast/static@C++,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
1 C++ 内存分区
- 栈区(stack)
- 堆区(heap)
- 代码区(.text[read-only for program])
- 常量区(.rodata[read-only for constant])
- 全局(静态)存储区
- .data: initialized / read & write
- .bss: uninitialized / read & write
进程的虚拟地址空间:
一个经典例子:
int a = 0; //全局初始化区 char *p; //全局未初始化区 void main() { int b; //栈区 char s[] = "abcd"; //栈区 char *p2; //栈区 char *p3 = "123456"; //123456在常量区,p3在栈区 static int c = 0; //全局(静态)初始化区 p1 = (char *)malloc(10); //分配所得的10字节区域位于堆区 p2 = (char *)malloc(20); //分配所得的20字节区域位于堆区 strcpy(p1, "123456"); }
2 四种显示类型转换算子
- static_cast<>
需要进行类型转换时, 首先考虑使用static_cast;
可以将右值转换成右值引用static_cast<int&&>(7); - reinterpret_cast<>
最危险的一种cast,应该尽可能地少用。 - const_cast<>
const_cast不会进行类型转换, 不过它可以给变量添加或去除const
属性
void aFunction(int* a) { cout << *a << endl; } int main() { int a = 10; const int* iVariable = &a; aFunction(const_cast<int*>(iVariable)); /*Since the function designer did not specify the parameter as const int*, we can strip the const-ness of the pointer iVariable to pass it into the function. Make sure that the function will not modify the value. */ return 0; }
- dynamic_cast<>
参考资料:
1 C++ casting
2 When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used?
3 C++:18---强制类型转换(static_cast、const_cast、dynamic_cast、reinterpret_cast)
3 static关键字
- static修饰的变量位于内存的全局/静态存储区, 程序退出才移出内存;
- 类中的static成员函数或成员变量, 可直接通过类来调用/获取, 不需要先实例化一个类对象.
这篇关于内存区/类型cast/static@C++的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-04-26高性能表格工具VTable总体构成-icode9专业技术文章分享
- 2024-04-16软路由代理问题, tg 无法代理问题-icode9专业技术文章分享
- 2024-04-16程序猿用什么锅-icode9专业技术文章分享
- 2024-04-16自建 NAS 的方案-icode9专业技术文章分享
- 2024-04-14ansible 在远程主机上执行脚本,并传入参数-icode9专业技术文章分享
- 2024-04-14ansible 在远程主机上执行脚本,并传入参数, 加上remote_src: yes 配置-icode9专业技术文章分享
- 2024-04-14ansible 检测远程主机的8080端口,如果关闭,则echo 进程已关闭-icode9专业技术文章分享
- 2024-04-14result 成功怎么写-icode9专业技术文章分享
- 2024-04-14stopped 状态设置为变量,由外部传递进来-icode9专业技术文章分享
- 2024-04-14为什么ansible执行远程脚本需要放到后台-icode9专业技术文章分享