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成员函数或成员变量, 可直接通过类来调用/获取, 不需要先实例化一个类对象.
- 我的微信
- 微信扫一扫
-
- 我的微信公众号
- 微信扫一扫
-
评论